记录瞬间
近段时间使用Springboot实现了文件的上传服务,但是在使用python的requests进行post上传时,总是报错。
比如:
1、Current request is not a multipart request
2、Required request part ‘fileName‘ is not present
3、MissingServletRequestPartException: Required request part ‘fileName‘ is not present
4、the request was rejected because no multipart boundary was found
后来进过多次查找,终于找到一个办法,将此问题解决。
// java实现的上传接口 /** * 上传文件 * @param file * @return */ @RequestMapping(value = "/uploadFile", method = RequestMethod.POST , consumes = "multipart/form-data") @ResponseBody public ResultData uploadFile(@RequestParam("fileName") MultipartFile file, @RequestParam("filePath") String zipPath) { String msg = "AIOps, Always Online! Always in!"; //判断文件是否为空 if (file.isEmpty()) { return new ResultData(false, msg, "失败了"); } String fileName = file.getOriginalFilename(); // 传入的文件名 String filePath = getOsPath(); // 获取本地基本路径 String path = filePath + "/" + fileName; System.out.println(fileName); System.out.println(zipPath); File dest = new File(path); //判断文件是否已经存在 if (dest.exists()) { return new ResultData(false, msg, "失败了"); } //判断文件父目录是否存在 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdir(); } try { file.transferTo(dest); // 保存文件 } catch (IOException e) { return new ResultData(false, msg, "失败了"); } return new ResultData(true, msg, "成功了"); } /** * 获取操作系统的基本路径 */ private String getOsPath(){ String osPath = "./"; if (System.getProperty("os.name").contains("Windows")) { osPath = config.getWindows_basedir(); } else if (System.getProperty("os.name").contains("Linux")) { osPath = config.getLinux_basedir(); } else { LOG.info("Unknown System..." + System.getProperty("os.name")); } return osPath; }
使用python进行连接的代码如下:
from urllib3 import encode_multipart_formdata import requests data = { "filePath": "path/for/test" } header = {} data[‘fileName‘] = ("fileName", open(r"D:\path\to\file", ‘rb‘).read()) encode_data = encode_multipart_formdata(data) data = encode_data[0] header[‘Content-Type‘] = encode_data[1] result = requests.post("http://localhost:8080/uploadFile", headers=header, data=data)
可以正常返回。
=============底线=============
Springboot实现上传文件接口,使用python的requests进行组装报文上传文件的方法
原文:https://www.cnblogs.com/wozijisun/p/11194541.html