CreateDirectoryIfNotExist(string filePath) 3 { 4 if (!Directory.Exists(filePath)) 5 { 6 Directory.CreateDirectory(filePath); 7 } ; 9 }
2.文件上传下载接口和图片大同小异。
1 using QX_Frame.App.WebApi; 2 using QX_Frame.FilesCenter.Helper; 3 using QX_Frame.Helper_DG; 4 using System.Collections.Generic; 5 using System.Diagnostics; 6 using System.IO; 7 using System.Linq; 8 using System.Net; 9 using System.Net.Http; 10 using System.Net.Http.Headers; 11 using System.Text; 12 using System.Threading.Tasks; 13 using System.Web; 14 using System.Web.Http; * 17 * author:qixiao 18 * create:2017-5-26 16:54:46 QX_Frame.FilesCenter.Controllers 21 { FilesController : WebApiControllerBase 23 { HttpResponseMessage Get(string fileName) 26 { 27 HttpResponseMessage result = null; ); 30 FileInfo foundFileInfo = directoryInfo.GetFiles().Where(x => x.Name == fileName).FirstOrDefault(); 31 if (foundFileInfo != null) 32 { 33 FileStream fs = new FileStream(foundFileInfo.FullName, FileMode.Open); 34 35 result = new HttpResponseMessage(HttpStatusCode.OK); 36 result.Content = new StreamContent(fs); ); ); 39 result.Content.Headers.ContentDisposition.FileName = foundFileInfo.Name; 40 } { 43 result = new HttpResponseMessage(HttpStatusCode.NotFound); 44 } result; 47 } Task<IHttpActionResult> Post() 51 { root = IO_Helper_DG.RootPath_MVC; newRoot = root + ; IO_Helper_DG.CreateDirectoryIfNotExist(newRoot); 59 60 List<string> fileNameList = new List<string>(); 61 62 StringBuilder sb = new StringBuilder(); fileTotalSize = 0; fileIndex = 1; HttpFileCollection files = HttpContext.Current.Request.Files; Task.Run(() => 72 { 73 foreach (var f in files.AllKeys) 74 { 75 HttpPostedFile file = files[f]; 76 if (!string.IsNullOrEmpty(file.FileName)) 77 { fileLocalFullName = newRoot + file.FileName; 80 81 file.SaveAs(fileLocalFullName); ); 84 85 FileInfo fileInfo = new FileInfo(fileLocalFullName); 86 87 fileTotalSize += fileInfo.Length; ); 90 91 fileIndex++; + fileLocalFullName); 94 } 95 } 96 }); Json(Return_Helper.Success_Msg_Data_DCount_HttpCode($, fileNameList, fileNameList.Count)); 100 } 101 } 102 }
实现了上述两个控制器代码以后,我们需要前端代码来调试对接,代码如下所示。