How to post a file via HTTP post in vb.net

2019-01-13 19:13发布

问题:

Having a problem with sending a file via HTTP post in vb.net. I am trying to mimic the following HTML so the vb.net does the same thing.

<form enctype="multipart/form-data" method="post" action="/cgi-bin/upload.cgi">
File to Upload:
<input type="file" name="filename"/>
<input type="submit" value="Upload" name="Submit"/>
</form>

Hope someone can help!

回答1:

I think what you are asking for is the ability to post a file to a web server cgi script from a VB.Net Winforms App.

If this is so this should work for you

Using wc As New System.Net.WebClient()
    wc.UploadFile("http://yourserver/cgi-bin/upload.cgi", "c:\test.bin")
End Using


回答2:

You may use HttpWebRequest if UploadFile (as OneShot says) does not work out.
HttpWebRequest as more granular options for credentials, etc

   FileStream rdr = new FileStream(fileToUpload, FileMode.Open);
   HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
   req.Method = "PUT"; // you might use "POST"
   req.ContentLength = rdr.Length;
   req.AllowWriteStreamBuffering = true;

   Stream reqStream = req.GetRequestStream();

   byte[] inData = new byte[rdr.Length];

   // Get data from upload file to inData 
   int bytesRead = rdr.Read(inData, 0, rdr.Length);

   // put data into request stream
   reqStream.Write(inData, 0, rdr.Length);

   rdr.Close();
   req.GetResponse();

   // after uploading close stream 
   reqStream.Close();


回答3:

Use this to get your file from the HTTP Post.

Request.Files["File"];


回答4:

You could use the

E.g:

In ASPX:
<Asp:FileUpload id="flUpload" runat="Server" />

In Code Behind:
if(flUpload.HasFile)
{
  string filepath = flUpload.PostedFile.FileName;
  flUpload.PostedFile.SaveAs(Server.MapPath(".\\") + file)
}