標籤:
在項目中我們有時候需要使用到其他第三方的api,而有些api要求我們上傳檔案,search一下,下面將結果記錄一下嘍!
含義 ENCTYPE="multipart/form-data" 說明:
通過 http 協議上傳檔案 rfc1867協議概述,jsp 應用舉例,用戶端發送內容構造
1、概述在最初的 http 協議中,沒有上傳檔案方面的功能。 rfc1867 (http://www.ietf.org/rfc/rfc1867.txt) 為 http 協議添加了這個功能。用戶端的瀏覽器,如 Microsoft IE, Mozila, Opera 等,按照此規範將使用者指定的檔案發送到伺服器。伺服器端的網頁程式,如 php, asp, jsp 等,可以按照此規範,解析出使用者發送來的檔案。Microsoft IE, Mozila, Opera 已經支援此協議,在網頁中使用一個特殊的 form 就可以傳送檔案。絕大部分 http server ,包括 tomcat ,已經支援此協議,可接受發送來的檔案。各種網頁程式,如 php, asp, jsp 中,對於上傳檔案已經做了很好的封裝。
2、上傳檔案執行個體,jsp例子:
1 <form action="gerry/publish/file" enctype="multipart/form-data" method="post">2 file:<input type="file" name="file"/><br/>3 <input type="submit" value="submit"/>4 </form>
View Code
如果上傳檔案,我們必須將enctype設定成"multipart/form-data",表示我們上傳的是一個位元據流。
3、Servlet中解析這個請求
1 boolean isMultipart = ServletFileUpload.isMultipartContent(req); 2 if (isMultipart) { 3 // 構造一個檔案上傳處理對象 4 FileItemFactory factory = new DiskFileItemFactory(); 5 ServletFileUpload upload = new ServletFileUpload(factory); 6 7 Iterator items; 8 try { 9 // 解析表單中提交的所有檔案內容10 items = upload.parseRequest(req).iterator();11 while (items.hasNext()) {12 FileItem item = (FileItem) items.next();13 System.out.println(item.getFieldName());14 System.out.println(item.isFormField());15 System.out.println(item.getString());16 17 if (!item.isFormField()) {18 // 取出上傳檔案的檔案名稱19 String name = item.getName();20 // 取得上傳檔案以後的儲存路徑21 String fileName = name.substring(name.lastIndexOf(‘\\‘) + 1, name.length());22 // 上傳檔案以後的儲存路徑23 String path = req.getRealPath("file") + File.separatorChar + fileName;24 25 // 上傳檔案26 File uploaderFile = new File(path);27 item.write(uploaderFile);28 }29 }30 } catch (Exception e) {31 resp.getOutputStream().write(("throw exception " + e.getMessage()).getBytes());32 }33 } else {34 resp.getOutputStream().write("is not this file upload".getBytes());35 }View Code
通過ServletFileUpload的parseRequest方法可以將檔案流和非檔案流全部解析出來。不用考慮HttpServletRequest中的資料流格式。
4、Spring中解析這個請求
在Spring中我們可以直接通過MultipartFile來擷取請求中的檔案流資訊。
1 @RequestMapping(value = "/gerry/publish/file") 2 @ResponseBody 3 public String upload1(MultipartFile file) { 4 String originalFileName = file.getOriginalFilename(); 5 String fileName = file.getName(); 6 System.out.println(originalFileName); 7 System.out.println(fileName); 8 System.out.println(file.getContentType()); 9 try {10 MyHttpClient.addPic(file.getBytes());11 } catch (Exception e) {12 return "failure, the exception msg is: " + e.getMessage();13 }14 return "success";15 }View Code
5、代碼中構造HttpClient請求,傳輸檔案
1 /** 2 * 傳輸檔案流bs 3 * 4 * @param bs 5 * 要傳輸的檔案流 6 */ 7 public static void addPic(byte[] bs) { 8 HttpClient httpClient = new DefaultHttpClient(); 9 HttpPost httpPost = new HttpPost(url);10 MultipartEntity entity = new MultipartEntity();11 entity.addPart("pic", new ByteArrayBody(bs, "pic"));12 try {13 // 添加其他的參數,可以是多個/零個14 entity.addPart("name", new StringBody("liuming92")); 15 } catch (UnsupportedEncodingException e1) {16 throw new RuntimeException(e1);17 }18 httpPost.setEntity(entity);19 try {20 HttpResponse httpResponse = httpClient.execute(httpPost);21 if (httpResponse != null) {22 String result = EntityUtils.toString(httpResponse.getEntity());23 System.out.println(result);24 }25 } catch (IOException e) {26 throw new RuntimeException(e);27 }28 }View Code
到這裡位置,java中上傳檔案以及向第三方傳輸檔案都實現啦。
HttpClient構造檔案上傳