java使用multipart/form-data POST上传文件
时间: 2023-10-03 09:06:36 浏览: 74
Java中可以使用HttpURLConnection来实现multipart/form-data POST上传文件。下面是一个示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void main(String[] args) throws Exception {
String apiUrl = "http://example.com/upload";
String filePath = "/path/to/file";
uploadFile(apiUrl, filePath);
}
public static void uploadFile(String apiUrl, String filePath) throws Exception {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=boundary");
File file = new File(filePath);
String fileName = file.getName();
FileInputStream inputStream = new FileInputStream(file);
OutputStream outputStream = conn.getOutputStream();
outputStream.write(("--boundary\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n" +
"Content-Type: application/octet-stream\r\n\r\n").getBytes());
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.write(("\r\n--boundary--").getBytes());
outputStream.flush();
outputStream.close();
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
}
}
```
在示例代码中,首先指定了上传文件的API地址和文件路径。然后通过HttpURLConnection打开连接,并设置请求方法为POST,Content-Type为multipart/form-data。接着读取文件内容,将文件内容写入请求的OutputStream中。最后获取响应码,如果响应码为200,则说明文件上传成功。