后端post请求发送MultipartFile文件
时间: 2024-06-07 17:03:30 浏览: 132
利用MultipartFile实现文件上传功能
5星 · 资源好评率100%
后端post请求发送MultipartFile文件可以使用Spring框架提供的MultipartFile类来实现,具体步骤如下:
1. 在前端页面中,使用input标签的type属性设置为file,并且name属性设置为文件参数名。
2. 在后端Controller中,使用@RequestParam注解获取前端传递的MultipartFile类型参数。
3. 创建一个java.net.URL对象来表示请求的URL地址,使用java.net.HttpURLConnection对象发送post请求并设置请求头,请求体中传递文件内容。
4. 获取请求响应,对响应进行处理。
示例代码如下:
```java
@PostMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
try {
URL url = new URL("http://example.com/upload");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(("--" + "----WebKitFormBoundary7MA4YWxkTrZu0gW" + "\r\n").getBytes());
os.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getOriginalFilename() + "\"\r\n").getBytes());
os.write(("Content-Type: " + file.getContentType() + "\r\n").getBytes());
os.write("\r\n".getBytes());
os.write(file.getBytes());
os.write("\r\n".getBytes());
os.write(("--" + "----WebKitFormBoundary7MA4YWxkTrZu0gW" + "--" + "\r\n").getBytes());
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
return "File upload failed with HTTP error code: " + responseCode;
}
} catch (Exception e) {
return "File upload failed with exception: " + e.getMessage();
}
}
```
阅读全文