写一个java用post请求上传请求中传的多个照片或视频或者音频的文件流至本机D盘tmp文件夹下
时间: 2024-03-02 13:54:18 浏览: 85
好的,以下是Java代码示例:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class UploadFileDemo {
public static void main(String[] args) throws IOException {
String url = "http://localhost:8080/upload"; // 上传文件的接口地址
String filePath1 = "C:\\test\\image1.jpg"; // 第一个文件路径
String filePath2 = "C:\\test\\video.mp4"; // 第二个文件路径
String filePath3 = "C:\\test\\audio.wav"; // 第三个文件路径
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=---Boundary");
OutputStream out = con.getOutputStream();
out.write(("\r\n---Boundary\r\n").getBytes());
out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath1.substring(filePath1.lastIndexOf("\\") + 1) + "\"\r\n").getBytes());
out.write(("Content-Type: image/jpeg\r\n\r\n").getBytes());
FileInputStream fis = new FileInputStream(filePath1);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
fis.close();
out.write(("\r\n---Boundary\r\n").getBytes());
out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath2.substring(filePath2.lastIndexOf("\\") + 1) + "\"\r\n").getBytes());
out.write(("Content-Type: video/mp4\r\n\r\n").getBytes());
fis = new FileInputStream(filePath2);
while ((len = fis.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
fis.close();
out.write(("\r\n---Boundary\r\n").getBytes());
out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath3.substring(filePath3.lastIndexOf("\\") + 1) + "\"\r\n").getBytes());
out.write(("Content-Type: audio/wav\r\n\r\n").getBytes());
fis = new FileInputStream(filePath3);
while ((len = fis.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
fis.close();
out.write(("\r\n---Boundary--\r\n").getBytes());
out.flush();
out.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response: " + response.toString());
}
}
```
请替换以下内容:
- `url`:上传文件的接口地址。
- `filePath1`、`filePath2`、`filePath3`:三个文件的路径。
运行该程序,即可将三个文件上传至服务器。在服务器端,你可以根据自己的需求来接收并处理这些文件。
阅读全文