優點:app
一、能夠實現一個或多個文件的上傳,也能夠接收普通的form表單數據。
二、簡單測試了一下,對內存的佔用仍是能夠忍受的,並且速度也能夠。偶爾會致使內存使用的上升並且不會降低,長時間後是否會降下來尚未測試。
關鍵點:
一、提交文件上傳的form的method屬性爲post,enctype屬性爲multipart/form-data。
二、input標籤須要有name屬性,不然取不到內容。ide
頁面代碼實現(部分):post
<form action="goods?id=addSecondPicture" method="post" enctype="multipart/form-data">
<tr>
<td height="60" class="title" rowspan="2">上傳圖片<br/>(限制二張)</td>
<td colspan="4"><input type="file" name="file1"><font color="red">(選填)</font></td>
<td></td>
</tr>
<tr>
<td colspan="4"><input type="file" name="file2"><font color="red">(選填)</font></td>
<td><input type="submit" value="上傳"></td>
</tr>
</form>測試
servlet映射:
this
<servlet>
<description></description>
<display-name>GoodServlet</display-name>
<servlet-name>GoodServlet</servlet-name>
<servlet-class>city.matcha.admin.servlet.GoodServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GoodServlet</servlet-name>
<url-pattern>/admin/goods</url-pattern>
</servlet-mapping>url
servlet代碼(關鍵部分):spa
List<Picture> pList = new ArrayList<Picture>();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024);
String SQLPath = "";
String rootPath = "";
String uploadPath = "";
try {
ServletFileUpload fu = new ServletFileUpload(factory);
fu.setSizeMax(2*1024*1024);
List fileitems = fu.parseRequest(request);
if(fileitems!=null){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD-HH-mm-ss");
rootPath = this.getServletContext().getRealPath("\\");
for(int i=0;i<fileitems.size();i++){
FileItem item = (FileItem)fileitems.get(i);
if(item.isFormField()){
continue;
}else{
String filePath = item.getName();
if(filePath!=null&&!filePath.trim().equals("")){
int point = filePath.lastIndexOf("\\");
String fileName = filePath.substring(point+1,filePath.length());
uploadPath = rootPath+"p_w_picpaths\\"+sdf.format(new Date())+fileName;
SQLPath = "..\\p_w_picpaths\\"+sdf.format(new Date())+fileName;
item.write(new File(uploadPath));
Picture pic = new Picture();
pic.setPurl(SQLPath);
pList.add(pic);
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}orm
若是有什麼不懂的地方,能夠留言,我會盡力回答~~~感謝光臨~~~圖片