我在使用FormData API上傳的網站中有一個canvas
元素。下面是我如何做到這一點:ReadAsMultipartAsync如何實際工作?
upload: function (e) {
var file = this.imagePreview.ui.canvas.get(0).toDataURL("image/jpeg")
.replace('data:image/jpeg;base64,', '');
if (file) {
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: app.getApiRoot + 'UserFiles/',
type: "post",
data: formData,
processData: false,
contentType: false,
error: function() {
$("#file_upload_result").html('there was an error while submitting');
}
});
}
}
在那裏我更換整個data:image/jpeg;base64,
業務按this post。
在後端我有以下多控制器:
public async Task<IHttpActionResult> PostUserFile()
{
string imageDir = ConfigurationManager.AppSettings["UploadedImageDir"];
var PATH = HttpContext.Current.Server.MapPath("~/" + imageDir);
var rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new CustomMultipartFormDataStreamProvider(PATH);
await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var files = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
return new UserFile(User.Identity.GetUserId(), info.Name, rootUrl + "/" + imageDir + "/" + info.Name, info.Length/1024);
});
db.UserFiles.AddRange(files);
db.SaveChangesAsync();
});
return Ok();
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
我在哪裏實現CustomMultipartFormDataStreamProvider
如下:
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path)
: base(path)
{ }
public override string GetLocalFileName(Headers.HttpContentHeaders headers)
{
var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ?
headers.ContentDisposition.FileName :
"NoName";
// This is here because Chrome submits files in quotation
// marks which get treated as part of the filename and get escaped
return name.Replace("\"\"", string.Empty);
}
}
不幸的是,在供給到ReadAsMultipartAsync
方法streamProvider
的FileData
是空:
而且我覺得有趣的另一件事是,上傳的二進制文件被轉義,因爲我從監視窗口中看到:
的%2f
對於/
字符轉義序列。
我簡直不能查明問題。任何人有任何建議?
請解釋回答更多的細節。 –
請嘗試學習如何使用Stackoverflow。編輯答案,不要在評論中添加信息。閱讀此:https://stackoverflow.com/help/how-to-answer –
聽起來很合理。讓我今天晚些時候實施它,並回到你身邊。 – seebiscuit