使用Java实现批量上传文件至服务器的代码
时间: 2023-06-06 09:08:57 浏览: 115
以下是Java实现批量上传文件至服务器的代码示例:
```
import java.io.*;
import java.net.*;
import java.util.*;
public class FileUploader {
private static String BOUNDARY = UUID.randomUUID().toString().substring(0, 10); //设置数据分隔线
public static void uploadFiles(String url, Map<String, String> paramMap, List<File> fileList) throws IOException {
URL uploadUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) uploadUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
//上传的表单参数部分
StringBuilder paramSb = new StringBuilder();
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
paramSb.append("--").append(BOUNDARY).append("\r\n");
paramSb.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"\r\n\r\n");
paramSb.append(entry.getValue()).append("\r\n");
}
out.write(paramSb.toString().getBytes());
//上传的文件部分
for (File file : fileList) {
String filename = file.getName();
StringBuilder sb = new StringBuilder();
sb.append("--").append(BOUNDARY).append("\r\n");
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"").append(filename).append("\"\r\n");
sb.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(filename)).append("\r\n\r\n");
out.write(sb.toString().getBytes());
InputStream in = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.write("\r\n".getBytes());
}
out.write(("--" + BOUNDARY + "--\r\n").getBytes());
out.flush();
out.close();
//读取服务器响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
conn.disconnect();
}
}
```
调用示例:
```
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("username", "testuser");
paramMap.put("password", "testpass");
List<File> fileList = new ArrayList<File>();
fileList.add(new File("D:/testfile1.txt"));
fileList.add(new File("D:/testfile2.txt"));
String url = "http://localhost:8080/upload";
FileUploader.uploadFiles(url, paramMap, fileList);
```
阅读全文