拥有一个 MVC 应用程序和一个单独的 WebAPI。使用 plupload,当 url 指向 MVC 控制器中的方法时,文件被 POST。
这是 Fiddler 展示的内容
POST /Home/HandleUpload/ HTTP/1.1
Host: localhost:50000
Connection: keep-alive
Content-Length: 38040
Origin: http://localhost:50000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryT4glpqFi5sbmY2KL
Accept: */*
Referer: http://localhost:50000/Home/Index
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
当我将 url 更改为指向 WebAPI 时,我收到 OPTIONS 请求而不是 POST,因此 API 方法不会被命中。
OPTIONS /api/v1/Files/HandleUpload HTTP/1.1
Host: localhost:60000
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:50000
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:50000/Home/Index
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
我在 plupload 配置上唯一改变的是 url。
这是我的方法。这两个项目都是一样的。
[HttpPost]
public HttpResponseMessage HandleUpload(int? chunk, string name)
{
var fileUpload = HttpContext.Current.Request.Files[0];
var uploadPath = HttpContext.Current.Server.MapPath("~/App_Data");
chunk = chunk ?? 0;
//write chunk to disk.
string uploadedFilePath = Path.Combine(uploadPath, name);
using (var fs = new FileStream(uploadedFilePath, chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
}