關於 詳情可以看 RFC1867:
他同樣是運用 Form-based File Upload in HTML
將檔案送到一個 Servlet,在 Servlet 中運用 apache commons 的 fileUpload 執行存檔動作
以下為簡圖說明之
在 Client 端部分不限於 Servlet 裡,已下看看Client程式的sample
//.....
String targetPath = "C:\\test.doc";
String url = "http://localhost:7001/OfficeService/office/receiveFiles"; //Server 端的 Servlet Url
File targetFile = new File(targetPath); //欲傳送之檔案
HttpClient client = new HttpClient();
MultipartPostMethod filePost = new MultipartPostMethod(targetUrl); // 傳送檔案時運用 MultipartPostMethod 將目標URL傳入
try {
if(!targetFile.exists()){
throw new FileNotFoundException(targetFile.getPath() + " -- not found -- ");
}else{
filePost.addParameter("param1", new String("1")); //寫入一個請求參數及其對應的值
filePost.addParameter("param2", new String("2")); //寫入一個請求參數及其對應的值
filePost.addPart(new FilePart("uploadFile", targetFile)); //新增欲上傳的檔案
client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); //設定逾期時間
int status = client.executeMethod(filePost); //執行 Request,並回傳一個 Http status
if (status == HttpStatus.SC_OK){
//pass file success
}else{
System.out.println("Pass file to OfficeService fail for Http status : " + status);
}
filePost.releaseConnection();
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (HttpException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
上面的 Code 很簡單,透過 commons 的 httpclient,可以不用程式設計師實際去寫檔案的 Post 封包
這個套件都幫你做好了
接著來看看 Server 端的 Servlet 如何收到這個 Request
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List fileItems = upload.parseRequest(request);
Iterator iter = fileItems.iterator();
while(iter.hasNext()){
FileItem item = (FileItem)iter.next();
if(item.isFormField()){
String name = item.getFieldName();
String value = item.getString();
System.out.println("FieldName : " + name + " Value : " + value);
}else{
String fileName = item.getName();
System.out.println("File name : " + fileName);
int fileSize = (int)item.getSize();
System.out.println("File size : " + fileSize);
//.....
}
}
} catch (FileUploadException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
關於 commons 的 fileUpload 操作我這邊不多說,可以看之前這篇文章
【Java Web】commons-fileUpload 使用方法

沒有留言:
張貼留言