我实现了上传功能:
MimeMultipart.cs
public class MimeMultipart : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(
new HttpResponseMessage(
HttpStatusCode.UnsupportedMediaType)
);
}
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
}
}
FileUploadResult.cs
public class FileUploadResult
{
public string LocalFilePath { get; set; }
public string FileName { get; set; }
public long FileLength { get; set; }
}
UploadMultipartFormProvider.cs
public class UploadMultipartFormProvider : MultipartFormDataStreamProvider
{
public UploadMultipartFormProvider(string rootPath) : base(rootPath) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
if (headers?.ContentDisposition != null)
{
return headers
.ContentDisposition
.FileName.TrimEnd('"').TrimStart('"');
}
return base.GetLocalFileName(headers);
}
}
UploadController.cs
[MimeMultipart]
[Route("images/upload")]
public HttpResponseMessage Post(HttpRequestMessage request, int companyId)
{
return CreateHttpResponse(request, () =>
{
HttpResponseMessage response = null;
var companyOld = _companiesRepository.GetSingle(companyId);
if (companyOld == null)
response = request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid company.");
else
{
var uploadPath = HttpContext.Current.Server.MapPath("~/Content/upload/companies/images");
var multipartFormDataStreamProvider = new UploadMultipartFormProvider(uploadPath);
// Read the MIME multipart asynchronously
Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);
string localFileName = multipartFormDataStreamProvider
.FileData.Select(multiPartData => multiPartData.LocalFileName).FirstOrDefault();
// Create response
if (localFileName != null)
{
var fileUploadResult = new FileUploadResult
{
LocalFilePath = localFileName,
FileName = Path.GetFileName(localFileName),
FileLength = new FileInfo(localFileName).Length
};
// update database
companyOld.Logo = fileUploadResult.FileName;
_companiesRepository.Edit(companyOld);
UnitOfWork.Commit();
response = request.CreateResponse(HttpStatusCode.OK, fileUploadResult);
}
}
return response;
});
}
Uploaded Image:图片大小101KB
Image after upload:图片大小31.8KB
错误:图像尺寸自动掉落。