java、 http模擬post上傳檔案到服務端 模擬form上傳檔案
阿新 • • 發佈:2019-01-07
需求是這樣的:
**1,前後端分離,前端對接pc軟體進行檔案同步的介面,後的springboot微服務進行檔案接收和處理。
2,軟體不能直接呼叫微服務的介面進行上傳,只能先走一下前端controller進行轉發過來()。
3,這樣就只能用httpclient進行http的轉發請求,先把檔案上傳來放到本地臨時處理下,在轉到微服務端進行處理。
4,post方式傳輸,單純的字元引數好處理,單純的檔案也能處理,2個都存在,會有一些小問題,尤其是報文那裡。**
- 第一步:同步檔案的介面
@ResponseBody
@RequestMapping(value="/res/upload" ,method=RequestMethod.POST, produces = "text/html;charset=UTF-8")
public String softUpload(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
MultipartFile dataFile = request.getFile("file");
String userName = request.getParameter ("userName");
String token = request.getParameter("token");
String fileName = dataFile.getOriginalFilename();
String ext = fileName.substring(fileName.lastIndexOf("."));
String saveFileName = "";
String relativePath = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd" );
relativePath = sdf.format(new Date()) + File.separator + UUID.randomUUID().toString().replace("-", "");
saveFileName = Configuration.getDataPath() + "/" + relativePath + ext;
// 將檔案儲存起來
FileUtils.writeByteArrayToFile(new File(saveFileName), dataFile.getBytes());
String doPost = HttpUtils.doPostWithFile(url, saveFileName,fileName,userName);
return doPost;
}
- 第二部:模擬post傳輸工具類
/**
* 提交file模擬form表單
* @param url
* @param savefileName
* @param fileName
* @param param
* @return
*/
public static String doPostWithFile(String url,String savefileName,String fileName, String param) {
String result = "";
try {
// 換行符
final String newLine = "\r\n";
final String boundaryPrefix = "--";
// 定義資料分隔線
String BOUNDARY = "========7d4a6d158c9";
// 伺服器的域名
URL realurl = new URL(url);
// 傳送POST請求必須設定如下兩行
HttpURLConnection connection = (HttpURLConnection) realurl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("Charset","UTF-8");
connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
// 頭
String boundary = BOUNDARY;
// 傳輸內容
StringBuffer contentBody =new StringBuffer("--" + BOUNDARY);
// 尾
String endBoundary ="\r\n--" + boundary + "--\r\n";
// 1. 處理普通表單域(即形如key = value對)的POST請求(這裡也可以迴圈處理多個欄位,或直接給json)
//這裡看過其他的資料,都沒有嘗試成功是因為下面多給了個Content-Type
//form-data 這個是form上傳 可以模擬任何型別
contentBody.append("\r\n")
.append("Content-Disposition: form-data; name=\"")
.append("param" + "\"")
.append("\r\n")
.append("\r\n")
.append(param)
.append("\r\n")
.append("--")
.append(boundary);
String boundaryMessage1 =contentBody.toString();
System.out.println(boundaryMessage1);
out.write(boundaryMessage1.getBytes("utf-8"));
// 2. 處理file檔案的POST請求(多個file可以迴圈處理)
contentBody = new StringBuffer();
contentBody.append("\r\n")
.append("Content-Disposition:form-data; name=\"")
.append("file" +"\"; ") // form中field的名稱
.append("filename=\"")
.append(fileName +"\"") //上傳檔案的檔名,包括目錄
.append("\r\n")
.append("Content-Type:multipart/form-data")
.append("\r\n\r\n");
String boundaryMessage2 = contentBody.toString();
System.out.println(boundaryMessage2);
out.write(boundaryMessage2.getBytes("utf-8"));
// 開始真正向伺服器寫檔案
File file = new File(savefileName);
DataInputStream dis= new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut =new byte[(int) file.length()];
bytes =dis.read(bufferOut);
out.write(bufferOut,0, bytes);
dis.close();
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 4. 從伺服器獲得回答的內容
String strLine="";
String strResponse ="";
InputStream in =connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while((strLine =reader.readLine()) != null)
{
strResponse +=strLine +"\n";
}
System.out.print(strResponse);
return strResponse;
} catch (Exception e) {
System.out.println("傳送POST請求出現異常!" + e);
e.printStackTrace();
}
return result;
}
- 第三部:服務接收端 處理檔案file
//新建資源這個是springboot介面
@RequestMapping(value = "/upload",method =RequestMethod.POST)
public ReturnResult<?> uploadRes( MultipartFile file, String param)throws Exception;
//這裡@RequestPart 註解直接接受file就可以了
public ReturnResult<?> uploadRes(@RequestPart("file") MultipartFile file,@RequestParam("param") String name) throws Exception{
logger.info("****新建資源****");
//處理邏輯
}