工具
smartupload.jar
使用
頁面部分
- 必須使用POST提價
- 表單屬性必須有
enctype="multipart/form-data"
<form action="toUpload" method="post" enctype="multipart/form-data" >
書名:<input type="text" name="bookName"/><br>
圖片:<input type="file" name="自定義名稱"/><br>
<input type="submit" value="提交"/>
</form>
檔案上傳
public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//上傳檔案
SmartUpload su=new SmartUpload();
//獲得pageContext物件
JspFactory factory=JspFactory.getDefaultFactory();
PageContext pagecontext=factory.getPageContext(this, request,response, null,false,1024,true);
su.initialize(pagecontext);
su.setCharset("utf-8");
//實現檔案資料的上傳
su.upload();
File file = su.getFiles().getFile(0);
//得到檔案的基本資訊
String filename=file.getFileName();
String type=file.getContentType();
String url="uploadfile/"+filename;
//將上傳檔案儲存到指定目錄
file.saveAs(url, SmartUpload.SAVE_VIRTUAL);
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
此時如果表單中有其他資料時,不能通過request直接獲取,需要通過SmartUpload物件獲取String name=su.getRequest().getParameter("bookName");並且該程式碼要在SmartUpload操作完成後新增
解決亂碼:
new String(name.getBytes("GBK"),"utf-8")
檔案下載
String name=request.getParameter("filename");
String url="uploadfile/"+name;
//將響應的內容設定為通用的二進位制流
response.setContentType("application/octet-stream");
//attachment 告訴瀏覽器以附件的方式下載檔案(彈出下載框)
name=URLEncoder.encode(name,"utf-8");
response.addHeader("Content-Disposition","attachment;filename="+name); request.getRequestDispatcher(url).forward(request, response);
//清空緩衝區:將服務端緩衝區的檔案內容,立即權並不傳送給客戶端
response.flushBuffer();