我目前正在迁移服务以使用来自mvc的asp.net web 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 / upload ,它应该开始上传我的文件。 这些方法已从现有的mvc Controller转换(返回 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/Api/Upload 415(不支持的媒体类型)
但是如果我注释掉 contentType:false,这一行并运行我的脚本我收到了一个错误的请求,虽然我的断点被点击了,但 UploadModel 实际上是空的。
有人可以建议解决方案吗?
干杯,
/ r3plica
答案 0 :(得分:0)
如果您认为该服务正在返回JSON,请尝试添加dataType: 'json',
并在你的ajax调用中替换以下错误handeling函数,以更好地理解你所面临的问题类型
error: function(xhr, exception) {
if (xhr.status === 0) {
alert('Not connected. Verify Login details or Network.');
} else if (xhr.status == 401) {
alert('Invalid Username or Password');
} else if (xhr.status == 404) {
alert('Requested page not found. [404]');
} else if (xhr.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + xhr.responseText);
}
}
注释掉内容类型
答案 1 :(得分:0)
我有同样的问题。在我的情况下,我不得不添加写文件的权限。我遵循了这个建议:https://stackoverflow.com/a/16948507/2549258我的问题415(不支持的媒体类型)消失了。