java写一段文件上传的代码
时间: 2023-03-22 08:01:46 浏览: 126
好的,以下是Java写一段文件上传的代码示例:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void main(String[] args) throws IOException {
String targetURL = "http://example.com/upload"; // 替换为实际的上传URL
String filePath = "path/to/file"; // 替换为实际的文件路径
File uploadFile = new File(filePath);
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
// 创建连接
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------7da2137580612");
// 构建请求体
String boundary = "---------------------------7da2137580612";
String fileName = uploadFile.getName();
String body = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n\r\n";
byte[] bodyBytes = body.getBytes("UTF-8");
byte[] fileBytes = new byte[(int) uploadFile.length()];
inputStream = new FileInputStream(uploadFile);
inputStream.read(fileBytes);
byte[] endBytes = ("\r\n--" + boundary + "--\r\n").getBytes("UTF-8");
byte[] dataBytes = new byte[bodyBytes.length + fileBytes.length + endBytes.length];
System.arraycopy(bodyBytes, 0, dataBytes, 0, bodyBytes.length);
System.arraycopy(fileBytes, 0, dataBytes, bodyBytes.length, fileBytes.length);
System.arraycopy(endBytes, 0, dataBytes, bodyBytes.length + fileBytes.length, endBytes.length);
// 发送请求
connection.getOutputStream().write(dataBytes);
// 处理响应
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// 上传成功
System.out.println("上传成功");
} else {
// 上传失败
System.out.println("上传失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
}
}
```
请注意将`targetURL`和`filePath`替换为实际的值,并确保请求头中的`boundary`值与请求体中的分隔符一致。此代码只是一个示例,具体实现可能因情况而异。
阅读全文