【问题标题】:Unable to Upload File through Spring boot REST API POST call from Python无法通过 Python 的 Spring Boot REST API POST 调用上传文件
【发布时间】:2021-09-24 12:09:14
【问题描述】:

我正在尝试通过 Python 脚本中的 POST REST API 调用(Spring boot)上传文件,因为我想自动化一些批处理作业。 但是出现错误“无法将类型 'java.lang.String' 的值转换为属性 'file' 所需的类型 'org.springframework.web.multipart.MultipartFile':找不到匹配的编辑器或转换策略]..

python 代码:

import requests
from requests.auth import HTTPBasicAuth
import json
from pathlib import Path


headers={'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9',
'Authorization': 'Bearer XXXX',
'Connection': 'keep-alive',
'Content-Type': 'multipart/form-data'}

fp = 'C:/inputs/inputfile.txt'
files = {'file': open(fp, 'rb')}

payload = {
    'integrator': 1,
    'version': 2, 
    'file': files
}


resp = requests.post("http://localhost:8080/api/v1/upload/text", params=payload, headers=headers , files=files)
print (resp.text)
print ("status code " + str(resp.status_code))

我的 API 代码库(Java Springboot REST API):

@PostMapping(value = "/upload/text", consumes = MediaTypes.MULTIPART_FORM_DATA)
    public List<String> uploadText(
    // @formatter:off
        @ModelAttribute
        TextUploadModel uploadModel,
        Principal principal
    // @formatter:on
    ) throws Exception {
        String userName = principal.getName();

        return service.uploadTextFile(uploadModel, userName);
    }

TextUploadModel.java 是一个带有字符串集成器、字符串版本和 MultipartFile 文件的 POJO。 我发现了类似的 SOF 帖子unanswered

【问题讨论】:

  • 你试过application/x-www-form-urlencoded而不是multipart/form-data吗?

标签: java python-3.x spring-boot python-requests


【解决方案1】:

问题可能与payload 字典的定义有关,您在其中包含了file 参数,并且很可能导致该参数被Spring 视为String,因为@987654321 @。

请从payload 中删除file 键:

payload = {
    'integrator': 1,
    'version': 2
}

files 参数中提供了您的文件上传信息:requests 将负责将每个参数类型放置在正确的位置,设置 Content-Type,并建立适当的多部分边界。

请考虑阅读this related SO question,它为如何处理requests 分段文件上传提供了很好的建议。

【讨论】:

  • 它确实帮助了我并解决了这个问题。谢谢!只是为了给帖子提供合乎逻辑的结论。正如建议的那样,我做了 2 处更改 1) 不再在标头中设置内容类型,2) 删除了有效负载的文件部分,问题解决了!
  • 欢迎您@lifeline2,非常感谢您的 cmets。这太棒了!我很高兴听到您设法解决了问题!
猜你喜欢
  • 2018-04-04
  • 2018-10-08
  • 2022-01-01
  • 1970-01-01
  • 2019-05-09
  • 2019-07-21
  • 1970-01-01
  • 2017-11-02
  • 2018-05-08
相关资源
最近更新 更多