前端页面代码:
<input type="file" class="file_control" /><br /> <input type="file" class="file_control" /><br /> <input type="file" class="file_control" /> <button id="btnUpload" type="button">上传</button> <script type="text/javascript"> $(document).ready(function () { $("#btnUpload").click(function () { var formdata = new FormData(); var files = $(".file_control"); $.each(files, function (index, domEle) { formdata.append("file" + index, domEle.files[0]); }); $.ajax({ url: '/api/Service/UpLoad', type: 'POST', cache: false, data: formdata, processData: false, contentType: false, success: function (data) { alert(data.success); }, error: function () { alert("error"); } }).done(function (res) { }).fail(function (res) { }); }); </script>
后端代码:
/// <summary> /// 文件上传 /// </summary> /// <param name="request"></param> /// <returns></returns> [HttpPost] [Route("api/Service/UpLoad")] public Task<HttpResponseMessage> UpLoad(HttpRequestMessage request) { if (!request.Content.IsMimeMultipartContent()) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); if (!ModelState.IsValid) throw new HttpResponseException(HttpStatusCode.BadRequest); string root = AppDomain.CurrentDomain.BaseDirectory + @"UploadFiles"; if (!Directory.Exists(root)) Directory.CreateDirectory(root); MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root); var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t => { if (t.IsFaulted || t.IsCanceled) return request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); HttpResponseMessage response = null; string filePath = root + @"" + DateTime.Now.ToString("yyyyMMdd"); if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath); foreach (var file in provider.FileData) { string fileName = file.Headers.ContentDisposition.FileName; if (Regex.IsMatch(fileName, @"^"".*""$")) fileName = fileName.Trim('"'); if (Regex.IsMatch(fileName, @"[\/]+")) fileName = Path.GetFileName(fileName); string extName = Path.GetExtension(fileName); string tempName = DateTime.Now.Ticks.ToString() + extName; File.Copy(file.LocalFileName, Path.Combine(filePath, tempName)); if (File.Exists(file.LocalFileName)) File.Delete(file.LocalFileName); // 转存阿里OSS、七牛云、腾讯云COS response = request.CreateResponse(HttpStatusCode.OK, new { success = true }); } return response; }); return task; }
*注:如果报IsFaulted=true的错误,基本上是因为你没给input起name造成的。