c#使用HttpWebRequest上传文件

使用c#的HttpRequest上传文件需要注意文件头部的的格式,以流的形式将数据传递到服务器那边但是post的格式要正确,不然服务器那边无法解 析所需要的数据总是返回错误。上传的代码全都在这里测试也通过了,要仔细看哦,在这里首先在本地将文件压缩,然后实现上传,花了很长时间问题才解决总算松 了口气啊,呵呵。

namespace WebInterface.FileOperation
{
public class UpLoadFile
{
public Login.Login UserLogin;
public string fileSuffixes = ".zip";
private NameValueCollection nameValueCollection = new NameValueCollection();

public UpLoadFile()
{
nameValueCollection.Add("ProductModel", "/client/product/savemodel/");
nameValueCollection.Add("UserDesign", "/client/design/save/");
}

/// <summary>
/// Zips the specified ziped floder.upload the file and compress the file,the prefix is .zip
/// </summary>
/// <param name="zipedFloder">The ziped floder.the floder needs to be compress and ziped name is as same as it </param>
/// <param name="zipFile">The zip file. </param>
/// <param name="compressionLevel">The compression level. </param>
/// <param name="blockSize">Size of the block. </param>
public String Zip(string zipedFloder, string zipFile, int compressionLevel, int blockSize)
{

if (!Directory.Exists(zipedFloder))
{
throw new Exception("The ziped file is not existed!");
}

// Crc32 crc = new Crc32();
string[] fileNames = Directory.GetFiles(zipedFloder);
string splitString = null;

ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(zipFile));

zipOutputStream.SetLevel(6);
foreach (string file in fileNames)
{
splitString = file.Substring(file.LastIndexOf("/") + 1);
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);

ZipEntry entry = new ZipEntry(splitString);
entry.Size = fs.Length;

fs.Close();
//crc.Reset();
// crc.Update(buffer);
//entry.Crc = crc.Value;
zipOutputStream.PutNextEntry(entry);
zipOutputStream.Write(buffer, 0, buffer.Length);
}

zipOutputStream.Finish();
zipOutputStream.Close();

return zipFile;
}


/// <summary>
/// Handles the response data.
/// </summary>
/// <param name="data">The data. </param>
/// <returns> </returns>
private object handleResponseData(string data)
{
object obj = null;
JObject jobject = JObject.Parse(data);
if (data.IndexOf(ErrorStatus.Result.fail.ToString()) != -1)
{
obj = new JsonSerializer().Deserialize(new JsonTokenReader(jobject), typeof(ErrorMessage));
}
else if (data.IndexOf(ErrorStatus.Result.ok.ToString()) != -1)
{
obj = new JsonSerializer().Deserialize(new JsonTokenReader(jobject), typeof(DesignFileUpLoad));

}
return obj;
}


/// <summary>
/// Ups the load.
/// </summary>
/// <param name="fileDirectory">The upload file. </param>
/// <param name="url">The URL.url should include 2 parameters
/// <session_id>session_id </session_id>
/// <description>description </description>
/// </param>
/// <param name="zipedFloderName">Name of the file for. </param>
/// <param name="contentType">Type of the content. </param>
/// <param name="queryString">The query string. </param>
/// <param name="cookie">The cookie. </param>
public object UserDesignFileUpload(string fileDirectory, NameValueCollection url, /*string zipedFile,*/ /*string contentType, CookieContainer cookie,*/string fileUploadType)
{

string zipedFloderName = fileDirectory.Substring(fileDirectory.LastIndexOf("/") + 1) + ".zip";

string zipedFileLocation = "d:/" + zipedFloderName;

Zip(fileDirectory, zipedFileLocation, 4096, 1);

string postUrl = WebUrlCollection.Prefix + WebUrlCollection.GetValueCollection()[fileUploadType];

if (zipedFloderName == null || zipedFloderName.Length == 0)
{
string defaultDirectory = Directory.GetCurrentDirectory() + "//";
zipedFloderName = "user_design_file";
}


Uri uri = new Uri(postUrl);

string boundaryValue = /*new String('-', 24) +*/ DateTime.Now.Ticks.ToString("x");
string boundary = "--"+boundaryValue;
//string boundary = DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);


request.ContentType = "/r/nmultipart/form-data; boundary=" + boundaryValue;

request.Method = "Post";
request.KeepAlive = true;

StringBuilder builder = new StringBuilder();

if (url != null)
{
foreach (string key in url)
{
builder.Append(boundary + "/r/nContent-Disposition: form-data; name=/"" + key + "/"/r/n/r/n" + url[key] + "/r/n");
}
}

builder.Append(boundary + "/r/nContent-Disposition: form-data; name=/"user_design_file/"; ");
builder.Append("filename=/"");

builder.Append(zipedFileLocation);

builder.Append("/"/r/nContent-Type: text/plain/r/n/r/n");


string postHeader = builder.ToString();

byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

//byte[] boundayBytes = Encoding.ASCII.GetBytes("/r/n" + boundary + "/r/n");
byte[] boundayBytes = Encoding.ASCII.GetBytes("/r/n" + boundary + "--/r/n");


FileStream fileStream = new FileStream(zipedFileLocation, FileMode.Open, FileAccess.Read, FileShare.None);
long length = postHeaderBytes.Length + fileStream.Length + boundayBytes.Length;

request.ContentLength = length;

Stream requestStream = request.GetRequestStream();

try
{
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

byte[] buffer = new Byte[(uint)Math.Min(4096, (int)fileStream.Length)];

int bytesRead = 0;
StringBuilder testbuilder = new StringBuilder();
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}

requestStream.Write(boundayBytes, 0, boundayBytes.Length);

}
catch (WebException e)
{
return e.ToString();
}
finally
{
if (requestStream != null)
{
requestStream.Close();
}
}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
StringBuilder responseData = new StringBuilder();


responseData.Append(reader.ReadLine());
responseStream.Close();

responseData.Replace("/*", " ");
responseData.Replace("*/", " ");
Debug.WriteLine("response data:" + responseData.ToString());
return handleResponseData(responseData.ToString());
}

}
}
整个文件上传的过程,测试已经通过。需要注意的是boundary的格式的使用,链接如下:
http://www.faqs.org/rfcs/rfc1867.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# WinForm 应用程序中,可以使用 HttpWebRequest 类来实现文件上传,具体步骤如下: 1. 创建 HttpWebRequest 对象,并设置请求参数。 ```csharp HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uploadUrl); request.Method = "POST"; request.ContentType = "multipart/form-data"; ``` 2. 构造要上传的文件数据。 ```csharp byte[] fileData = File.ReadAllBytes(filePath); string fileName = Path.GetFileName(filePath); string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; string formdata = string.Format(formdataTemplate, "file", fileName); byte[] formdataBytes = Encoding.UTF8.GetBytes(formdata); byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); ``` 3. 将文件数据写入请求流中。 ```csharp Stream requestStream = request.GetRequestStream(); requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); requestStream.Write(formdataBytes, 0, formdataBytes.Length); requestStream.Write(fileData, 0, fileData.Length); byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); requestStream.Write(trailer, 0, trailer.Length); requestStream.Close(); ``` 4. 发送请求并获取响应。 ```csharp HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string responseString = reader.ReadToEnd(); reader.Close(); response.Close(); ``` 完整的码示例如下: ```csharp public void UploadFile(string uploadUrl, string filePath) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uploadUrl); request.Method = "POST"; request.ContentType = "multipart/form-data"; byte[] fileData = File.ReadAllBytes(filePath); string fileName = Path.GetFileName(filePath); string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; string formdata = string.Format(formdataTemplate, "file", fileName); byte[] formdataBytes = Encoding.UTF8.GetBytes(formdata); byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); Stream requestStream = request.GetRequestStream(); requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); requestStream.Write(formdataBytes, 0, formdataBytes.Length); requestStream.Write(fileData, 0, fileData.Length); byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); requestStream.Write(trailer, 0, trailer.Length); requestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string responseString = reader.ReadToEnd(); reader.Close(); response.Close(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值