调用Web API将文件上传到服务器的方法(.Net Core)

        最近遇到一个将Excel通过Web API存到服务器的问题,其中涉及到Excel的读取、调用API、Web  API怎么进行接收。

一、 Excel的读取、调用API

        Excel读取以及调用API的代码,文件的读取很简单,但是在调用API的时候需要注意,常用的Get和Post两个请求方式是由一定区别的,即在传输数据时Get有大小限制而Post没有(详细内容请自行查找了解更多)。所以本人选用了Post来传输文件流,同时,在此过程中,将所有字符进行编码后运用表单提交来进行。最后要提的一点:文件流我单独进行了处理(对其进行了Base64编码)保证数据的准确性和不乱吗。

 1 using System;
 2 using System.IO;
 3 using System.Net.Http;
 4 using System.Text;
 5 using System.Web;
 6 
 7 namespace ReadExcelAndUpload
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             string path = "test.xls";//文件路径
14             string fileName = "test.xls";//文件名
15             string apiUrl = "http://localhost:8016/api/Upload/DownFile";//调用的API
16 
17             //读取文件
18             using (var stream = File.OpenRead(path))
19             {
20                 Upload(stream,fileName,apiUrl);//上传文件到API接口
21 
22             }
23         }
24 
25 
26 
27         /// <summary>
28         /// 上传文件到API接口
29         /// </summary>
30         /// <param name="stream">文件流</param>
31         /// <param name="fileName">文件名称</param>
32         /// <param name="apiUrl">API接口</param>
33         private static void Upload(FileStream stream, string fileName, string apiUrl)
34         {
35 
36 
37             string url = apiUrl;
38 
39             using (var client = new HttpClient())
40             {
41 
42                 string para = "";//参数
43                 byte[] pReadByte = new byte[0];
44                 BinaryReader r = new BinaryReader(stream);
45                 r.BaseStream.Seek(0, SeekOrigin.Begin);    //将文件指针设置到文件开
46 
47                 pReadByte = r.ReadBytes((int)r.BaseStream.Length);//文件流
48 
49                 para = string.Format("stream={0}&fileName={1}", Convert.ToBase64String(pReadByte).Replace("+", " "), fileName);
50                 byte[] bytePara = Encoding.UTF8.GetBytes(para);
51 
52 
53                 using (StreamContent sc = new StreamContent(new MemoryStream(bytePara)))
54                 {
55                     sc.Headers.ContentLength = bytePara.Length;
56                     sc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");//application/x-www-form-urlencoded
57                     var respMsg = client.PostAsync(url, sc);
58                     HttpResponseMessage responseMessage = respMsg.Result;
59                 }
60             }
61 
62         }
63     }
64 }
View Code 

二、Web  API怎么进行接收

         1、接收的API接口,参数中特性不清楚的可以点击https://docs.microsoft.com/zh-cn/aspnet/core/web-api/?view=aspnetcore-2.2

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Http;
 6 using Microsoft.AspNetCore.Mvc;
 7 
 8 namespace SaveFile.Controllers
 9 {
10     [Route("api/[controller]")]
11     [ApiController]
12     public class UploadController : ControllerBase
13     {
14 
15         /// <summary>
16         /// 下载文件的API
17         /// </summary>
18         /// <param name="stream"></param>
19         /// <param name="fileName"></param>
20         [HttpPost("DownFile", Name = "DownFile")]
21         public void DownFile([FromForm]string stream, [FromForm] string fileName)
22         {
23             string dir = @"D:\temp";
24             FileHelper.SaveFile(Convert.FromBase64String(@stream.Replace(" ", "+")), fileName, dir);//通过Base64编码解码 需要对加号进行处理
25 
26 
27 
28         }
29 
30 
31     }
32 }
View Code

  2、对得到的文件流进行处理的方法,简单的文件流操作方式,没啥可说的。

 1 using Microsoft.AspNetCore.Mvc;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.IO;
 5 using System.Linq;
 6 using System.Threading.Tasks;
 7 
 8 namespace SaveFile.Controllers
 9 {
10     public class FileHelper
11     {
12         public static void SaveFile(byte[] pReadByte, string fileName, string saveUrl)
13         {
14 
15             string dir = @saveUrl;
16             if (!Directory.Exists(dir))
17             {
18                 Directory.CreateDirectory(dir);
19             }
20 
21             string url = dir + "\\" + fileName;
22             if (!File.Exists(url))
23             {
24                 File.Delete(url);
25             }
26             //创建本地文件写入流
27             Stream stream = new FileStream(url, FileMode.OpenOrCreate);
28            
29             if (pReadByte.Length > 0)
30             {
31                 stream.Write(pReadByte, 0, pReadByte.Length);
32 
33             }
34             stream.Close();
35             stream.Dispose();
36 
37         }
38 
39 
40     }
41 }
View Code
 
 

       最后,希望大家看了代码之后能帮大家解决遇到的问题。整个过程并不复杂,主要部分是文件流上传API接口这个关键环节(涉及到编码以及对文件流操作等内容)。

  

转载于:https://www.cnblogs.com/cjygrow/p/10077956.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值