欢迎来到山村网

WebApi2 文件图片上传与下载功能详解

2019-03-09 12:30:47浏览:373 来源:山村网   
核心摘要:Asp.Net Framework webapi2 文件上传与下载 前端界面采用Ajax的方式执行一、项目结构1.App_Start配置了跨域访问,以免请求时候因

Asp.Net framework webapi2 文件上传与下载 前端界面采用Ajax的方式执行

一、项目结构

WebApi2 文件图片上传与下载功能详解 山村

1.App_Start配置了跨域访问,以免请求时候因跨域问题不能提交。具体的跨域配置方式如下,了解的朋友请自行略过。

跨域配置:NewGet安装dll Microsofg.AspNet.Cors

然后在App_Start 文件夹下的WebApiConfig.cs中写入跨域配置代码。

public static class WebApiConfig  {    public static void Register(HttpConfiguration config)    {      // Web API configuration and services      // Web API routes      config.MapHttpAttributeRoutes();      // Web API configuration and services      //跨域配置 //need reference from nuget      config.EnableCors(new EnableCorsAttribute("*", "*", "*"));      config.Routes.MapHttpRoute(        name: "DefaultApi",        routeTemplate: "api/{controller}/{id}",        defaults: new { id = RouteParameter.Optional }      );      //if config the global filter input there need not write the attributes      //config.Filters.Add(new App.WebApi.Filters.ExceptionAttribute_DG());    }  }

跨域就算完成了,请自行测试。

2.新建两个控制器,一个PicturesController.cs,一个FilesController.cs当然图片也是文件,这里图片和文件以不同的方式处理的,因为图片的方式文件上传没有成功,所以另寻他路,如果在座的有更好的方式,请不吝赐教!

二、项目代码

1.我们先说图片上传、下载控制器接口,这里其实没什么好说的,就一个Get获取文件,参数是文件全名;Post上传文件;直接上代码。

using QX_frame.App.WebApi;using QX_frame.FilesCenter.Helper;using QX_frame.Helper_DG;using QX_frame.Helper_DG.Extends;using System;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Linq;using System.Net;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;using System.Web.Http;namespace QX_frame.FilesCenter.Controllers{  public class PicturesController : WebApiControllerbase  {    //Get : api/Pictures    public HttpResponseMessage Get(string fileName)    {      HttpResponseMessage result = null;      DirectoryInfo directoryInfo = new DirectoryInfo(IO_Helper_DG.RootPath_MVC + @"Files/Pictures");      FileInfo foundFileInfo = directoryInfo.GetFiles().Where(x => x.Name == fileName).FirstOrDefault();      if (foundFileInfo != null)      {        FileStream fs = new FileStream(foundFileInfo.FullName, FileMode.Open);        result = new HttpResponseMessage(HttpStatusCode.OK);        result.Content = new StreamContent(fs);        result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");        result.Content.Headers.ContentDisposition.FileName = foundFileInfo.Name;      }      else      {        result = new HttpResponseMessage(HttpStatusCode.NotFound);      }      return result;    }    //POST : api/Pictures    public async Task<IHttpActionResult> Post()    {      if (!Request.Content.IsMimeMultipartContent())      {        throw new Exception_DG("unsupported media type", 2005);      }      string root = IO_Helper_DG.RootPath_MVC;      IO_Helper_DG.CreateDirectoryIfNotExist(root + "/temp");      var provider = new MultipartFormDataStreamProvider(root + "/temp");      // Read the form data.       await Request.Content.ReadAsMultipartAsync(provider);      List<string> fileNameList = new List<string>();      StringBuilder sb = new StringBuilder();      long fileTotalSize = 0;      int fileIndex = 1;      // This illustrates how to get the file names.      foreach (MultipartFileData file in provider.FileData)      {        //new folder        string newRoot = root + @"Files/Pictures";        IO_Helper_DG.CreateDirectoryIfNotExist(newRoot);        if (File.Exists(file.LocalFileName))        {          //new fileName          string fileName = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2);          string newFileName = Guid.NewGuid() + "." + fileName.Split('.')[1];          string newFullFileName = newRoot + "/" + newFileName;          fileNameList.Add($"Files/Pictures/{newFileName}");          FileInfo fileInfo = new FileInfo(file.LocalFileName);          fileTotalSize += fileInfo.Length;          sb.Append($" #{fileIndex} Uploaded file: {newFileName} ({ fileInfo.Length} bytes)");          fileIndex++;          File.Move(file.LocalFileName, newFullFileName);          Trace.WriteLine("1 file copied , filePath=" + newFullFileName);        }      }      return Json(Return_Helper.Success_Msg_Data_DCount_HttpCode($"{fileNameList.Count} file(s) /{fileTotalSize} bytes uploaded successfully!   Details -> {sb.ToString()}", fileNameList, fileNameList.Count));    }  }}

里面可能有部分代码在Helper帮助类里面写的,其实也仅仅是获取服务器根路径和如果判断文件夹不存在则创建目录,这两个代码的实现如下:

 public static string RootPath_MVC     {       get { return System.Web.HttpContext.Current.Server.MapPath("~"); }     }//create Directory    public static bool CreateDirectoryIfNotExist(string filePath)    {      if (!Directory.Exists(filePath))      {        Directory.CreateDirectory(filePath);      }      return true;    }

2.文件上传下载接口和图片大同小异。

using QX_frame.App.WebApi;using QX_frame.FilesCenter.Helper;using QX_frame.Helper_DG;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Linq;using System.Net;using System.Net.Http;using System.Net.Http.Headers;using System.Text;using System.Threading.Tasks;using System.Web;using System.Web.Http;namespace QX_frame.FilesCenter.Controllers{  public class FilesController : WebApiControllerbase  {    //Get : api/Files    public HttpResponseMessage Get(string fileName)    {      HttpResponseMessage result = null;      DirectoryInfo directoryInfo = new DirectoryInfo(IO_Helper_DG.RootPath_MVC + @"Files/Files");      FileInfo foundFileInfo = directoryInfo.GetFiles().Where(x => x.Name == fileName).FirstOrDefault();      if (foundFileInfo != null)      {        FileStream fs = new FileStream(foundFileInfo.FullName, FileMode.Open);        result = new HttpResponseMessage(HttpStatusCode.OK);        result.Content = new StreamContent(fs);        result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");        result.Content.Headers.ContentDisposition.FileName = foundFileInfo.Name;      }      else      {        result = new HttpResponseMessage(HttpStatusCode.NotFound);      }      return result;    }    //POST : api/Files    public async Task<IHttpActionResult> Post()    {      //get server root physical path      string root = IO_Helper_DG.RootPath_MVC;      //new folder      string newRoot = root + @"Files/Files/";      //check path is exist if not create it      IO_Helper_DG.CreateDirectoryIfNotExist(newRoot);      List<string> fileNameList = new List<string>();      StringBuilder sb = new StringBuilder();      long fileTotalSize = 0;      int fileIndex = 1;      //get files from request      HttpFileCollection files = HttpContext.Current.Request.Files;      await Task.Run(() =>      {        foreach (var f in files.AllKeys)        {          HttpPostedFile file = files[f];          if (!string.IsNullOrEmpty(file.FileName))          {            string fileLocalFullName = newRoot + file.FileName;            file.SaveAs(fileLocalFullName);            fileNameList.Add($"Files/Files/{file.FileName}");            FileInfo fileInfo = new FileInfo(fileLocalFullName);            fileTotalSize += fileInfo.Length;            sb.Append($" #{fileIndex} Uploaded file: {file.FileName} ({ fileInfo.Length} bytes)");            fileIndex++;            Trace.WriteLine("1 file copied , filePath=" + fileLocalFullName);          }        }      });      return Json(Return_Helper.Success_Msg_Data_DCount_HttpCode($"{fileNameList.Count} file(s) /{fileTotalSize} bytes uploaded successfully!   Details -> {sb.ToString()}", fileNameList, fileNameList.Count));    }  }}

实现了上述两个控制器代码以后,我们需要前端代码来调试对接,代码如下所示。

<!doctype><head>  <script src=http://www.shancun.net/skin/default/image/nopic.gif  <!--<script src=http://www.shancun.net/skin/default/image/nopic.gif  <!--<script src=http://www.shancun.net/skin/default/image/nopic.gif  <script>    $(document).ready(function () {      var appDomain = "http://localhost:3997/";      $("#btn_fileUpload").click(function () {                //-------asp.net webapi fileUpload        //        var formData = new FormData($("#uploadForm")[0]);        $.ajax({          url: appDomain + 'api/Files',          type: 'POST',          data: formData,          async: false,          cache: false,          contentType: false,          processdata: false,          success: function (data) {            console.log(JSON.stringify(data));          },          error: function (data) {            console.log(JSON.stringify(data));          }        });        //----end asp.net webapi fileUpload        //----.net core webapi fileUpload        // var fileUpload = $("#files").get(0);        // var files = fileUpload.files;        // var data = new FormData();        // for (var i = 0; i < files.length; i++) {        //    data.append(files[i].name, files[i]);        // }        // $.ajax({        //   type: "POST",        //   url: appDomain+'api/Files',        //   contentType: false,        //   processdata: false,        //   data: data,        //   success: function (data) {        //     console.log(JSON.stringify(data));        //   },        //   error: function () {        //     console.log(JSON.stringify(data));        //   }        // });        //--------end net core webapi fileUpload                // $.ajaxFileUpload({        //   type: 'post',        //   url: appDomain + 'api/Files',        //   secureuri: false,        //   fileElementId: 'files',        //   success: function (data) {        //     console.log(JSON.stringify(data));        //   },        //   error: function () {        //     console.log(JSON.stringify(data));        //   }        // });      });      //end click    })  </script></head><title></title><body>  <article>    <header>      <h2>article-form</h2>    </header>    <p>      <form action="/" method="post" id="uploadForm" enctype="multipart/form-data">        <input type="file" id="files" name="files" placeholder="file" multiple>file-multiple属性可以选择多项<br><br>        <input type="button" id="btn_fileUpload" value="fileUpload">      </form>    </p>  </article></body>

至此,我们的功能已全部实现,下面我们来测试一下:

可见,文件上传成功,按预期格式返回!

下面我们测试单图片上传->

然后我们按返回的地址进行访问图片地址。

发现并无任何压力!

下面测试多图片上传->

完美~

至此,我们已经实现了WebApi2文件和图片上传,下载的全部功能。

这里需要注意一下Web.config的配置上传文件支持的总大小,我这里配置的是最大支持的文件大小为1MB

<requestFiltering>  <requestLimits maxAllowedContentLength="1048576" /></requestFiltering>  <system.webServer>   <handlers>    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />    <remove name="OPTIONSVerbHandler" />    <remove name="TRACEVerbHandler" />    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />   </handlers>   <security>   <requestFiltering>    <requestLimits maxAllowedContentLength="1048576" /><!--1MB-->    </requestFiltering>  </security>  </system.webServer>

原文链接:http://www.cnblogs.com/qixiaoyizhan/p/6912321.html

(责任编辑:豆豆)
下一篇:

路由器端口映射设置

上一篇:

redhat/Centosrpmforge安装

  • 信息二维码

    手机看新闻

  • 分享到
打赏
免责声明
• 
本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们 xfptx@outlook.com