如何解决Postman中文件上传错误?

问题描述 投票:0回答:5

我在项目中使用 webapi 进行文件上传。我正在用邮递员进行测试。但是,Request.Content.IsMimeMultipartContent() 始终返回 false。

邮递员截图:

文件上传控制器代码:

public async Task<HttpResponseMessage> UserImageUpload()
    {
        try
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var userImageUploadPath = HttpContext.Current.Server.MapPath(CommonParameters.UserProfileImageServerPath);
            var streamProvider = new CustomMultipartFormDataStreamProvider(userImageUploadPath);
            await Request.Content.ReadAsMultipartAsync(streamProvider);

            var files = new List<string>();
            foreach (MultipartFileData file in streamProvider.FileData)
            {
                files.Add(Path.GetFileName(file.LocalFileName));
            }

            return Request.CreateResponse(HttpStatusCode.OK, files);
        }
        catch (Exception exception)
        {
            logger.ErrorFormat("An error occured in UserImageUpload() Method - Class:FileUploadController - Message:{0}", exception);
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }
file-upload asp.net-web-api2 postman asyncfileupload
5个回答
10
投票

这是邮递员错误。尝试删除 Content-Type 标头。当发送实际的帖子时,浏览器将自动添加适当的标题并创建边界。


2
投票

Postman 中的标头中无需提及 Content-Type,我尝试发送不带 Content-Type 的附件,这对我来说效果很好。 当我使用

Content-Type: multipart/formdata
时,它会抛出一个错误,提示“无法得到任何响应”。邮递员也使用
Content-Type →text/plain; charset=utf-8
发送您的文件附件。


2
投票

有几件事需要考虑:

    如果您使用
  1. Postman

    ,请不要发送任何 Content Type 标头

  2. Body(表单数据)

    中为您选择的文件指定表单数据Key(PFB屏幕截图供您参考)


1
投票

0
投票

© www.soinside.com 2019 - 2024. All rights reserved.