使用HttpWebRequest上传文件—无法上传

本文关键字:文件 使用 HttpWebRequest | 更新日期: 2023-09-27 18:05:51

下面是代码-上传文件到uri。我不能上传。有什么问题吗?

string fileToUpload = @"F:''upload_file.txt";
FileStream rdr = new FileStream(fileToUpload, FileMode.Open);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:8080/upload.txt"); //Given URI is exists
req.Method = "POST"; 
req.ContentLength = rdr.Length;
req.AllowWriteStreamBuffering = true;
Stream reqStream = req.GetRequestStream();
Console.WriteLine(rdr.Length);                
byte[] inData = new byte[rdr.Length];
// Get data from upload file to inData 
int bytesRead = rdr.Read(inData, 0, (int)rdr.Length);
// put data into request stream
reqStream.Write(inData, 0, (int)rdr.Length);
rdr.Close();
req.GetResponse();
// after uploading close stream 
reqStream.Close(); 

使用HttpWebRequest上传文件—无法上传

乍一看,我认为您选择的@应用于定义特定字符串的文件可能存在问题。不需要转义字符。反之亦然,下面的字符串在您的web请求。

所以你应该更正为@"F:'upload_file.txt";"F:''upload_file.txt";