用java写一段代码用于上传包含建筑模型的文件夹到根目录下面
时间: 2024-02-23 18:02:46 浏览: 56
好的,以下是用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.MalformedURLException;
import java.net.URL;
public class UploadModel {
public static void main(String[] args) {
String uploadUrl = "http://localhost:8080/upload"; // 上传接口地址
String folderPath = "/path/to/folder"; // 文件夹路径
String rootPath = "/"; // 根目录路径
// 遍历文件夹
File folder = new File(folderPath);
if (folder.isDirectory()) {
File[] files = folder.listFiles();
for (File file : files) {
String fileName = file.getName();
String filePath = file.getAbsolutePath();
String uploadFilePath = rootPath + fileName;
// 上传文件
try {
URL url = new URL(uploadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
String boundary = "-----------------------------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
// 文件参数
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: application/octet-stream\r\n\r\n");
byte[] headerBytes = sb.toString().getBytes("UTF-8");
byte[] footerBytes = ("\r\n--" + boundary + "--\r\n").getBytes("UTF-8");
long contentLength = headerBytes.length + file.length() + footerBytes.length;
// 开始上传
conn.setRequestProperty("Content-Length", String.valueOf(contentLength));
conn.connect();
conn.getOutputStream().write(headerBytes);
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[8192];
int len = -1;
while ((len = is.read(buffer)) != -1) {
conn.getOutputStream().write(buffer, 0, len);
}
is.close();
conn.getOutputStream().write(footerBytes);
// 上传成功
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println("上传成功:" + filePath + " -> " + uploadFilePath);
} else {
System.out.println("上传失败:" + filePath + " -> " + uploadFilePath);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
需要注意的是,这段代码仅供参考,具体的上传接口实现可能有所不同,也需要根据实际需求进行相应的调整。
阅读全文