我目前正在迁移服务,利用从MVC asp.net网页API。 我有这个ApiController
[Authorize]
public class UploadController : ApiController
{
private readonly ObjectService service;
private readonly string companyId;
public UploadController()
{
this.companyId = "D49AA22B-3476-4FAC-8BEF-38F53F9378F3";
this.service = new ObjectService(ConfigurationManager.AppSettings["AWSAccessKey"], ConfigurationManager.AppSettings["AWSSecretKey"], this.companyId);
}
// POST api/upload/5
[HttpPost]
[Route("api/upload")]
public IHttpActionResult StartUpload(UploadModel model)
{
try
{
var id = Guid.NewGuid().ToString();
if (!service.Exists(model.File.FileName))
{
service.Add(id);
var stream = new MemoryStream();
var caller = new AsyncMethodCaller(service.Upload);
model.File.InputStream.CopyTo(stream);
var result = caller.BeginInvoke(id, stream, model.File.FileName, new AsyncCallback(CompleteUpload), caller);
}
else
throw new Exception("This file already exists. If you wish to replace the asset, please edit it.");
return Ok(id);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
public void CompleteUpload(IAsyncResult result)
{
var caller = (AsyncMethodCaller)result.AsyncState;
var id = caller.EndInvoke(result);
//this.service.Remove(id);
}
// GET api/upload/progress/5
[HttpGet]
[Route("api/upload/progress/{id}")]
public IHttpActionResult GetCurrentProgress(string id)
{
try
{
var progress = service.GetStatus(id);
return Ok(progress);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
this.service.Dispose();
base.Dispose(disposing);
}
}
正如你所看到的,如果我做一个帖子API /上传应该开始上传我的文件。 这些方法已经从现有的MVC控制器转换(其返回JsonResult代替IHttpActionResult)
我UploadModel看起来是这样的:
public class UploadModel
{
public HttpPostedFileBase File { get; set; }
public string FileName { get; set; }
}
和我的jQuery看起来是这样的:
function uploadFile() {
var file = $("#File")[0].files[0];
if (file) {
var fileName = "test/" + $('input[type=file]').val().split('\\').pop();
var data = new FormData();
data.append("File", file);
data.append("FileName", fileName);
$.ajax({
url: "/Api/Upload",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function (data) {
console.log("uploading");
console.log(data);
createCategory(fileName);
},
error: function () {
displayAlert(".message", "There was a problem when uploading the file!", "danger");
}
});
} else {
createCategory();
}
};
当我运行这段代码,我得到的错误
POST HTTP://r3plica.localhost:3892 /原料药/上传 415(不支持的媒体类型)
但如果我注释掉的contentType:假的,运行我的脚本,我得到一个错误的请求,虽然我的断点被击中,在UploadModel实际上是空。
任何人都可以提出一个解决办法?
干杯,
/ r3plica