public dynamic Upload(UploadFileDto model) { return(UploadAsync(model).Result); }
public async Task <dynamic> UploadAsync([FromUri] UploadFileDto model) { return(await UploadAsync(Request, model)); }
private async Task <dynamic> UploadAsync(HttpRequestMessage request, UploadFileDto model) { if (request == null) { throw new ArgumentNullException("request"); } if (model == null) { throw new ArgumentNullException("model"); } // Check if the request contains multipart/form-data. bool isMime = request.Content.IsMimeMultipartContent(); if (!isMime) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } try { var mr = new MessageResult(); var fileUrls = new List <string>(); var provider = new MultipartMemoryStreamProvider(); await request.Content.ReadAsMultipartAsync(provider); foreach (HttpContent content in provider.Contents) { //now read individual part into STREAM var stream = await content.ReadAsStreamAsync(); if (stream.Length != 0) { string fileName = GetFileName(content.Headers); if (fileName == null) { continue; } string extension = GetFileExtension(fileName); bool isAllowed = CheckAllowedExtensions(extension); if (!isAllowed) { throw new NotSupportedException("不支持的文件格式:" + extension); } //var virtualPathRoot = request.GetRequestContext().VirtualPathRoot; var server = HttpContext.Current.Server; //var saveFolder = server.MapPath("~/App_Data/uploads"); var saveFolder = server.MapPath(model.VirtualFolder); if (!string.IsNullOrWhiteSpace(model.FileName)) { fileName = model.FileName; } var savePath = Path.Combine(saveFolder, fileName); //Deletion exists file if (File.Exists(savePath)) { File.Delete(savePath); } MakeSureFolderExist(saveFolder); using (Stream saveFileStream = File.OpenWrite(savePath)) { await stream.CopyToAsync(saveFileStream); stream.Close(); } } else { fileUrls.Add(null); } } mr.Message = "上传完成"; mr.Success = true; mr.Data = fileUrls; return(mr); } catch (Exception ex) { return(request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } }