webapi文件上传和下载

时间:2021-12-16 13:31:01

文件上传我们可以做上传文件保存到图片与导入数据,下载可以下载多样的文件。

上传:实例是单个文件导入

NopiHelper:地址

①简单的上传图片进行保存,方法跟MVC中的一样

 <form name="form1" method="post" enctype="multipart/form-data" action="../api/upload/PostFormData2">
        <div>
            <label for="caption">Image Caption</label>
            <input name="caption" type="text" />
        </div>
        <div>
            <label for="image1">Image File</label>
            <input name="image1" type="file" />
        </div>
        <div>
            <input type="submit" value="Submit" />
        </div>
    </form>
 [HttpPost]
        public async Task<IHttpActionResult> PostFormData2()
        {
            IList<string> paths = new List<string>();
            var files = HttpContext.Current.Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[0];
                string filePath = $@"upload/{DateTime.Now.ToString("yyyyMMddssfff")}_{file.FileName}";
                DirectoryInfo rootDir2 = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory);
                string path = System.IO.Path.Combine(
                     rootDir2.FullName, filePath);
                var dir = Path.GetDirectoryName(path);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                file.SaveAs(path);
                paths.Add(path);
            }
            return await Task.FromResult(Ok(new { errcode = 0, data = paths }));
        }

 

导入数据:这里需要我们Nuget:Npoi

  [HttpPost]
        public async Task<IHttpActionResult> UploadFile()
        {
            try
            {
                //得到上传的文件
                HttpPostedFile file = HttpContext.Current.Request.Files[0];
          //转DataTable DataTable dt
= NopiHelper.ExcelToTable(file.InputStream, 0, 0, Path.GetExtension(file.FileName));
          //通过DataTable转实体 List
<TVideosurveillance> list = NopiHelper.Mapper<TVideosurveillance>(dt); foreach (TVideosurveillance item in list) { TVideosurveillance model = await dbOracle.TVideosurveillances.AsQueryable().FirstAsync(x => x.Dwname == item.Dwname); if (model == null) { model.Dwname = item.Dwname; model.Dwcode = item.Dwcode; model.Code = item.Code; model.Ip = item.Ip; model.Sbtdmc = item.Sbtdmc; double[] vs = WGS84Helper.bd09togcj02(item.Coordx.ToDouble(), item.Coordy.ToDouble()); double[] vs2 = WGS84Helper.gcj02towgs84(vs[0], vs[1]); model.Coordx = vs2[0] + ""; model.Coordy = vs2[1] + ""; dbOracle.TVideosurveillances.Insert(model); } } return await Task.FromResult(Ok(new { errcode = 0, data = "成功" })); } catch (Exception ex) { return await Task.FromResult(Ok(new { errcode = 0, data = ex.Message })); } }

 

 

下载(导出):webapi中需要我们对  HttpResponseMessage 进行设置

  /// <summary>
        /// 下载只能使用Get方式,需要我们返回 HttpResponseMessage
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<HttpResponseMessage> Test()
        {
            DataTable dt = NopiHelper.Mapper<TestA>();
            //导出的名字,需要带扩展名 *.xls   *.xlsx
            string fileName = "测试.xls";
            Stream stream = NopiHelper.StreamFromDataTable(dt, fileName);
            //设置状态
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            //内容
            httpResponseMessage.Content = new StreamContent(stream);
            //类型
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
            //响应内容的值,附件形式
            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = HttpUtility.UrlEncode(Path.GetFileName(fileName))
            };
            return await Task.FromResult(httpResponseMessage);
        }

 

MS Excel具有以下观察到的MIME类型:

  • application/vnd.ms-excel (官方)
  • application/msexcel
  • application/x-msexcel
  • application/x-ms-excel
  • application/x-excel
  • application/x-dos_ms_excel
  • application/xls
  • application/x-xls
  • application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (XLSX)