java实现大文件上传代码实现
时间: 2023-11-18 18:04:26 浏览: 108
java 实现大文件上传
3星 · 编辑精心推荐
以下是一个简单的Java代码示例,展示了如何实现大文件上传:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
class FileUploader {
private static final int BUFFER = 4096;
public static void uploadFile(StringUrl, String filePath) throws IOException {
File file = new File(filePath);
FileInputStream inputStream = new FileInputStream(file);
URL url = new URL(serverUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println("File uploaded successfully.");
} else {
System.out.println("File upload failed. Response code: " + responseCode);
}
outputStream.close();
inputStream.close();
}
public static void main(String[] args) {
String serverUrl = "http://example.com/upload"; // 替换为实际的服务器URL
String filePath = "path/to/file"; // 替换为实际的文件路径
try {
uploadFile(serverUrl, filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,`uploadFile`方法接收服务器URL和文件路径作为参数,并使用`HttpURLConnection`发送POST请求将文件内容上传到服务器。需要注意的是,这只是一个简单的示例,实际应用中可能需要添加错误处理、断点续传等功能。
阅读全文