WebApi2 文件图片上传与下载功能(2)

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; /** * author:qixiao * create:2017-5-26 16:54:46 * */ 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="https://www.jb51.net/jquery-3.2.0.min.js"></script> <!--<script src="https://www.jb51.net/jquery-1.11.1.js"></script>--> <!--<script src="https://www.jb51.net/ajaxfileupload.js"></script>--> <script> $(document).ready(function () { var appDomain = "http://localhost:3997/"; $("#btn_fileUpload").click(function () { /** * 用ajax方式上传文件 ----------- * */ //-------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.js 方式上传文件 * */ // $.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="https://www.jb51.net/" method="post" enctype="multipart/form-data"> <input type="file" placeholder="file" multiple>file-multiple属性可以选择多项<br><br> <input type="button" value="fileUpload"> </form> </p> </article> </body>

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

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

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

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

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

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

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

发现并无任何压力!

下面测试多图片上传->

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

完美~

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

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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdpdfw.html