文件请求方法
/*** 上传图文消息内的图片 获取url* 富文本内的图片** @param file*/public static String uploadMediaGetUrl(File file) throws IOException {if (!file.exists()) {return null;}String responseData = null;try {String url = "http://localhost:8503/file/upload";OkHttpClient client = new OkHttpClient();MediaType mediaType = MediaType.parse("multipart/form-data");RequestBody fileBody = RequestBody.create(mediaType, file);RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", file.getName(), fileBody) // 中间参数为文件名.build();Request request = new Request.Builder().url(url).post(requestBody).build();Response response = client.newCall(request).execute();responseData = response.body().string();} catch (Exception e) {e.printStackTrace();}JSONObject jsonObject = JSONObject.parseObject(responseData);JSONObject data = (JSONObject)jsonObject.get("data");return (String)data.get("fileId");}//测试 ,传入文件或者图片public static void main(String[] args) throws IOException {File file = new File("d:\\Documents\\WeChat Files\\wxid_u2tkiuv7461q22\\FileStorage\\File\\123\\123.png");String fileId = WxApiUtils.uploadMediaGetUrl(file);System.out.println("fileId-----" + fileId);}
文件接收方法
/*** 文件上传Controller** @author xushuang* @date 2023-06-08*/
@Api(tags = "文件上传")
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FsFileController extends BaseController {private final FsFileService fsFileService;private static final Logger log = LoggerFactory.getLogger(FsFileController.class);@ApiOperation("文件上传")@PostMapping("upload")public AjaxResult upload(MultipartFile file) {log.info("文件上传");return AjaxResult.success(fsFileService.upload(file));}
携带多个参数的情况