使用webapi上传文件需要引用ICSharpCode.SharpZipLib.Zip;
前端代码示例:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title></title> 6 <meta charset="utf-8" /> 7 8 <script src="Resource/jquery-1.10.2.min.js"></script> 9 <script> 10 $(function () { 11 $("#upload").click(function () { 12 $("#imgWait").show(); 13 var formData = new FormData($(‘form‘)[0]); 14 // formData.append("myfile", document.getElementById("file1").files[0]); 15 $.ajax({ 16 url: "https://localhost:81/api/file/uploadfile/111", 17 type: "POST", 18 data: formData, 19 /** 20 *必须false才会自动加上正确的Content-Type 21 */ 22 contentType: false, 23 /** 24 * 必须false才会避开jQuery对 formdata 的默认处理 25 * XMLHttpRequest会对 formdata 进行正确的处理 26 */ 27 processData: false, 28 success: function (data) { 29 if (data.status == "true") { 30 alert("上传成功!"); 31 } 32 if (data.status == "error") { 33 alert(data.msg); 34 } 35 $("#imgWait").hide(); 36 }, 37 error: function (data) { 38 alert("上传失败!"); 39 $("#imgWait").hide(); 40 } 41 }); 42 }); 43 }); 44 </script> 45 46 </head> 47 <body> 48 <form id="uploadForm" enctype="multipart/form-data"> 49 选择文件:<input type="file" id="file1" name="file" /><br /> 50 <input type="button" id="upload" value="上传" /> 51 <img src="wait.gif" style="display:none" id="imgWait" /> 52 </form> 53 </body> 54 55 </html>
前后端分离,处理跨域访问,在web.config文件的<system.webserver></system.webserver>节点下添加跨域设置
1 <httpProtocol> 2 <customHeaders> 3 <add name="Access-Control-Allow-Origin" value="*" /> 4 <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS"/> 5 <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" /> 6 </customHeaders> 7 </httpProtocol>
后端代码:
1 /// <summary> 2 /// 上传文件 3 /// </summary> 4 /// <returns></returns> 5 [HttpPost] 6 [Route("api/fileinfo/uploadfile/{folderpath}/{bussinessid}")] 7 public async Task<string> UploadFile(string folderpath, string bussinessid) 8 { 9 string rtValue = string.Empty; 10 ErrorCode code = null; 11 try 12 { 13 IFileInfoLogic logic = LZFactory<IFileInfoLogic>.CreateInstance("Lz.Product.ELManage.BLL.FileInfoLogic,Lz.Product.ELManage.BLL"); 14 if (!bussinessid.Equals("0")) 15 { 16 bool flag = logic.DeleteFile(bussinessid); 17 } 18 19 if (!Request.Content.IsMimeMultipartContent("form-data")) 20 { 21 throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 22 } 23 //文件上传相对路径 24 string releativePath = string.Format("/Resource/{0}/", folderpath); 25 string temprelativepath = "/Resource/temp/"; 26 //文件上传物理路径 27 string uploadFolderPath = HostingEnvironment.MapPath(releativePath); 28 string temppath= HostingEnvironment.MapPath(temprelativepath); 29 30 //如果路径不存在,创建路径 31 if (!Directory.Exists(uploadFolderPath)) 32 Directory.CreateDirectory(uploadFolderPath); 33 if (!Directory.Exists(temppath)) 34 Directory.CreateDirectory(temppath); 35 string keyId = Guid.NewGuid().ToString(); 36 //执行provider文件上传成功 37 var provider = new WithExtensionMultipartFormDataStreamProvider(temppath, keyId); 38 39 // Read the form data. 40 await Request.Content.ReadAsMultipartAsync(provider); 41 42 // This illustrates how to get the file names. 43 string fileName = string.Empty; 44 45 //FileInfoLogic logic = new FileInfoLogic(); 46 //可处理批量上传 47 foreach (var file in provider.FileData) 48 { 49 //处理上传文件可能存在文件名相同的情况 50 //完整路径 51 string fullpath = file.LocalFileName; 52 //获取文件名 53 fileName = Path.GetFileName(fullpath); 54 //上传文件名 55 string fileEextension = Path.GetExtension(fileName); 56 //实际存放文件名 57 string dtnow = DateTime.Now.ToString("yyyyMMddHHmmssfff"); 58 //存放路径(相对) 59 string virpath = temprelativepath + dtnow + fileEextension; 60 61 string files = uploadFolderPath + dtnow + fileEextension; 62 File.Copy(fullpath, files); 63 64 65 //文件信息写入数据库 66 bussinessid = bussinessid == "0" ? Guid.NewGuid().ToString() : bussinessid; 67 FileInfoModel fileEntity = new FileInfoModel() 68 { 69 FileId = keyId, 70 FileName = fileName, 71 RealName= dtnow + fileEextension, 72 FilePath = releativePath, 73 FileSize = "15kb",//(!string.IsNullOrEmpty(fullpath) ? DirFileHelper.GetFileSize(fullpath.Replace("\"", "")).ToString():""), 74 FileExtensions = fileEextension, 75 FileType = fileEextension.Replace(".", ""), 76 CreatTime = DateTime.Now, 77 BussinessId = bussinessid 78 }; 79 logic.InsertFileInfo(fileEntity); 80 code = ErrorCodeManager.GetCode("0"); 81 //返回文件信息 82 FileEntity entity = new FileEntity() 83 { 84 FileName = fileName, 85 FileUrl = releativePath +fileName, 86 FileId = keyId, 87 KeyValue = bussinessid, 88 RealFilePath= releativePath+ dtnow + fileEextension 89 }; 90 JavaScriptSerializer serializer = new JavaScriptSerializer(); 91 rtValue = serializer.Serialize(entity); 92 string[] tempfiles = CommonHelper.GetFiles(temppath); 93 foreach (var item in tempfiles) 94 { 95 try 96 { 97 File.Delete(item);//删除临时文件 98 } 99 catch (Exception ex) 100 { 101 continue; 102 } 103 } 104 } 105 } 106 catch (Exception ex) 107 { 108 //LogManager.Logger.Error("文件上传失败"); 109 code = ErrorCodeManager.GetCode("26001"); 110 rtValue = "文件上传失败"; 111 } 112 return rtValue; 113 } 114 115 /// <summary> 116 /// 上传文件 117 /// </summary> 118 public class WithExtensionMultipartFormDataStreamProvider : MultipartFormDataStreamProvider 119 { 120 public string fileName { get; set; } 121 /// <summary> 122 /// 重写文件名 123 /// </summary> 124 /// <param name="headers"></param> 125 /// <returns></returns> 126 public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) 127 { 128 string fileName = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? GetValidFileName(headers.ContentDisposition.FileName) : ""; 129 //return fileName + extension; 130 return fileName; 131 } 132 133 public WithExtensionMultipartFormDataStreamProvider(string rootPath, string filename) 134 : base(rootPath) 135 { 136 //fileName = filename; 137 } 138 private string GetValidFileName(string filePath) 139 { 140 char[] invalids = System.IO.Path.GetInvalidFileNameChars(); 141 return String.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd(‘.‘); 142 } 143 }