使用Web API上传时不支持的媒体类型(Unsupported media type when u

2019-10-19 15:58发布

我目前正在迁移服务,利用从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

Answer 1:

尝试添加dataType: 'json',如果你认为该服务返回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);
       }
       }

注释掉的内容类型



Answer 2:

我遇到过同样的问题。 在我来说,我不得不添加权限写入文件。 我也跟着这样的建议: https://stackoverflow.com/a/16948507/2549258和我的415(不支持的媒体类型)的问题消失了。



文章来源: Unsupported media type when uploading using web api