给我一个java编写的大文件上传的代码
时间: 2023-03-02 14:08:01 浏览: 94
以下是一个Java编写的大文件上传的示例代码:
```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 {
private static final int BUFFER_SIZE = 4096;
public static void upload(String targetURL, String filePath) throws IOException {
File uploadFile = new File(filePath);
URL url = new URL(targetURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestProperty("Content-Length", String.valueOf(uploadFile.length()));
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setChunkedStreamingMode(BUFFER_SIZE);
try (InputStream inputStream = new FileInputStream(uploadFile)) {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
connection.getOutputStream().write(buffer, 0, bytesRead);
}
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 文件上传成功
System.out.println("文件上传成功!");
} else {
// 文件上传失败
System.out.println("文件上传失败,响应代码为:" + responseCode);
}
connection.disconnect();
}
}
```
使用方法:
```java
String targetURL = "http://example.com/upload";
String filePath = "/path/to/file";
FileUploader.upload(targetURL, filePath);
```
其中,`targetURL` 是文件上传的目标 URL,`filePath` 是要上传的文件的路径。请根据实际情况修改这两个变量的值。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)