用Java HttpURLConnection模仿html表單上傳檔案
阿新 • • 發佈:2021-04-26
1 獲取html請求報文
使用POST上傳檔案
前端標籤樣例
<form action="http://www.baidu.com/" method="post" enctype="multipart/form-data">
<input type="text" name="myText" /><br />
<input type="file" name="upload1" /><br />
< input type="file" name="upload2" /><br />
<input type="submit" />
</form>
為了實驗所需,我們建立兩個檔案file1.txt和file2.txt,內容分別為“This is file1.”及“This is file2, it’s bigger.”。在文字框裡寫上“hello world”,並選擇這兩個檔案,提交,則會看到瀏覽器傳遞了如下資料:
POST http://www.baidu.com/ HTTP/1.1
Host: www. baidu.com
Content-Length: 495
Content-Type: multipart/form-data; boundary=---------------------------7db2d1bcc50e6e
-----------------------------7db2d1bcc50e6e
Content-Disposition: form-data; name="myText"
hello world
-----------------------------7db2d1bcc50e6e
Content-Disposition: form-data; name="upload1"; filename="C:\file1.txt"
Content-Type: text/plain
This is file1.
-----------------------------7db2d1bcc50e6e
Content-Disposition: form-data; name="upload2"; filename="C:\file2.txt"
Content-Type: text/plain
This is file2, it's longer.
-----------------------------7db2d1bcc50e6e--
2 通過Java URL讀取本地圖片傳送給服務端
程式碼如下
public void sendFiles(String path,String requestPath){
String boundary = "--test";
String format = "\r\n";
String formatTwo = "\r\n\r\n";
try {
URL url = new URL(requestPath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(4000);
conn.setRequestProperty("Connection","Keep-Alive");
conn.setRequestProperty("Charset","UTF-8");
conn.setRequestProperty("Content-Type","multipart/form-data; boundary="+boundary);
conn.connect();
OutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(formatTwo.getBytes(StandardCharsets.UTF_8));
InputStream in =null;
File file = new File(path);
for(File file1 : file.listFiles()){
if(file1.isDirectory()){continue;}
out.write(("--"+boundary+format).getBytes(StandardCharsets.UTF_8));
String contentType = "Content-Disposition: form-data; name=\"files\"; filename="+"\""+file1.getName()+"\"";
out.write((contentType+format).getBytes(StandardCharsets.UTF_8));
contentType = "Content-Type: text/plain";
out.write((contentType+formatTwo).getBytes(StandardCharsets.UTF_8));
in = new FileInputStream(file1);
byte[] by = new byte[1024];
int temp = -1;
while ((temp=in.read(by))!=-1){
out.write(by);
}
out.write(format.getBytes(StandardCharsets.UTF_8));
}
out.write(("--"+boundary).getBytes(StandardCharsets.UTF_8));
in.close();
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println("---line---"+line);
}
}catch (Exception e){
e.printStackTrace();
}
}
注意多個檔案用分割字串分割時在前一定要加- -
3 服務端接收檔案
程式碼如下
@ResponseBody
@RequestMapping("/upload/files")
public String uploadFiles(@RequestParam("files") MultipartFile[] files){
for (MultipartFile multipartFile : files){
String fileName = multipartFile.getOriginalFilename();
try {
File file = new File(filePath + File.separator + fileName);
multipartFile.transferTo(file);
}catch (Exception e){
e.printStackTrace();
}
}
return "成功";
}