本文主要是介绍C# 采用 multipart/form-data 方式上传文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/// <summary>
/// 上传文件接口
/// </summary>
/// <param name="dictParam">上传参数</param>
/// <param name="fileUrl">文件的地址</param>
/// <param name="url">请求接口地址</param>
/// <param name="encoding">字符编码格式</param>
/// <param name="keyName">文件参数的参数名称</param>
/// <returns></returns>
public static string UploadRequest(Dictionary<string, object> dictParam, string fileUrl, Encoding encoding, string url, string keyName, Dictionary<string, string> headerPars)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebHeaderCollection header = request.Headers;
request.Method = "post";
//读取文件信息
FileStream fileStream = new FileStream(fileUrl, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
byte[] UpdateFile = bytes;//转换为二进制
if (UpdateFile.Length == 0)
{
return "上传文件无效";
}
string Boundary = "--WebKitFormBoundary39B5a5e2FWoGbphs";
//构造POST请求体
StringBuilder PostContent = new StringBuilder("");
//获取文件名称
string filename = "";
filename = Path.GetFileName(fileUrl);
//组成普通参数信息
foreach (KeyValuePair<string, object> item in dictParam)
{
PostContent.Append("--" + Boundary + "\r\n")
.Append("Content-Disposition: form-data; name=\"" + item.Key + "\"" + "\r\n\r\n" + (string)item.Value + "\r\n");
}
byte[] PostContentByte = encoding.GetBytes(PostContent.ToString());
//处理文件参数信息
StringBuilder FileContent = new StringBuilder();
FileContent.Append("--" + Boundary + "\r\n")
.Append("Content-Disposition:form-data; name=\"" + keyName + "\";filename=\"" + filename + "\"" + "\r\n\r\n");
byte[] FileContentByte = encoding.GetBytes(FileContent.ToString());
request.ContentType = "multipart/form-data;boundary=" + Boundary;
if (headerPars != null && headerPars.Keys.Count > 0)
{
foreach (var item in headerPars)
{
request.Headers.Add(item.Key, item.Value);
}
}
byte[] ContentEnd = encoding.GetBytes("\r\n--" + Boundary + "--\r\n");//请求体末尾,后面会用到
//定义请求流
Stream myRequestStream = request.GetRequestStream();
myRequestStream.Write(PostContentByte, 0, PostContentByte.Length);//写入参数
myRequestStream.Write(FileContentByte, 0, FileContentByte.Length);//写入文件信息
myRequestStream.Write(UpdateFile, 0, UpdateFile.Length);//文件写入请求流中
myRequestStream.Write(ContentEnd, 0, ContentEnd.Length);//写入结尾
myRequestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encodingth = response.ContentEncoding;
if (encodingth == null || encodingth.Length < 1)
{
encodingth = "UTF-8"; //默认编码,根据需求自己指定
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encodingth));
string retString = reader.ReadToEnd();
return retString;
}
这篇关于C# 采用 multipart/form-data 方式上传文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!