编程语言
首页 > 编程语言> > C# .Net Core 在后台Post单个文件调用接口的方法

C# .Net Core 在后台Post单个文件调用接口的方法

作者:互联网

 1         /// <summary>
 2         /// Post单个文件
 3         /// </summary>
 4         /// <typeparam name="T">返回结果</typeparam>
 5         /// <param name="url">提交地址</param>
 6         /// <param name="fieldName">参数名称</param>
 7         /// <param name="file">文件信息</param>
 8         /// <returns></returns>
 9         public static T PostSingleFile<T>(string url ,string fieldName, PostFileItem file)
10         {
11             Stream fs = file.FileStream;
12             if (!fs.CanRead)
13             {
14                 return default;
15             }
16             byte[] buffer = new byte[fs.Length];
17             fs.Read(buffer, 0, (int)fs.Length);
18             fs.Close();
19 
20             string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
21             string PREFIX = "--", LINE_END = "\r\n";
22 
23             StringBuilder sb = new StringBuilder();
24             sb.Append(PREFIX + boundary + LINE_END);
25             sb.Append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + file.FileName + "\"" + LINE_END);
26             sb.Append("Content-Type: " + file.ContentType + LINE_END + LINE_END);
27             WebRequest request = WebRequest.Create(url);
28             request.Method = "POST";
29             request.ContentType = "multipart/form-data;boundary=" + boundary;
30             Stream dataStream = request.GetRequestStream();
31             dataStream.Write(Encoding.UTF8.GetBytes(sb.ToString()), 0, Encoding.UTF8.GetByteCount(sb.ToString()));
32             dataStream.Write(buffer, 0, buffer.Length);
33             dataStream.Write(Encoding.UTF8.GetBytes(LINE_END + PREFIX + boundary + PREFIX + LINE_END), 0, Encoding.UTF8.GetByteCount(LINE_END + PREFIX + boundary + PREFIX + LINE_END));
34             dataStream.Close();
35 
36             WebResponse webResponse = request.GetResponse();
37             Stream newStream = webResponse.GetResponseStream();
38 
39             StreamReader rdr = new StreamReader(newStream);
40             var result = rdr.ReadToEnd();
41 
42             if (!string.IsNullOrEmpty(result))
43                 return JsonUtil.ConvertJsonToObject<T>(result);
44 
45             return default;
46         }

提交文件使用的工具类:

 1     /// <summary>
 2     /// 提交文件请求参数
 3     /// </summary>
 4     public class PostFileItem
 5     {
 6         /// <summary>
 7         /// 文件数据流
 8         /// </summary>
 9         public Stream FileStream { get; set; }
10         /// <summary>
11         /// 文件名称
12         /// </summary>
13         public string FileName { get; set; }
14         /// <summary>
15         /// 文件类别
16         /// </summary>
17         public string ContentType { get; set; }
18     }

 

标签:Core,fs,END,string,C#,PREFIX,boundary,Net,LINE
来源: https://www.cnblogs.com/SuperJason/p/15796683.html