java写一个文件上传的工具类
时间: 2023-03-22 08:01:46 浏览: 74
好的,我可以回答这个问题。以下是一个简单的Java文件上传的工具类:
```java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void uploadFile(String targetUrl, String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new IllegalArgumentException("File " + filePath + " does not exist");
}
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n";
HttpURLConnection connection = (HttpURLConnection) new URL(targetUrl).openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(("--" + boundary + CRLF).getBytes());
outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + CRLF).getBytes());
outputStream.write(("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName()) + CRLF).getBytes());
outputStream.write(("Content-Transfer-Encoding: binary" + CRLF).getBytes());
outputStream.write(CRLF.getBytes());
byte[] buffer = new byte[4096];
int bytesRead;
InputStream inputStream = FileUploader.class.getResourceAsStream(filePath);
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.write(CRLF.getBytes());
outputStream.write(("--" + boundary + "--" + CRLF).getBytes());
outputStream.close();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed to upload file to " + targetUrl + ", response code: " + connection.getResponseCode());
}
}
}
```
这个工具类使用Java的HttpURLConnection实现文件上传,可以上传指定路径下的文件到指定URL。你只需要调用`uploadFile`方法并传入目标URL和文件路径即可完成文件上传。注意,此工具类仅供参考,具体实现可能需要根据你的需求进行调整。