SP Servlet 文件上傳我們首先需要準(zhǔn)備兩個(gè)jar包
需要在你的classpath中引入最新的 commons-fileupload.x.x.jar 包文件衔瓮。
下載地址為:http://commons.apache.org/fileupload/
需要在你的classpath中引入最新的 commons-io-x.x.jar 。
下載地址為:http://commons.apache.org/io/
創(chuàng)建項(xiàng)目
1.png
2.png
3.png
在創(chuàng)建項(xiàng)目最后一步記得選上 Generate web.xml deployment descriptor
創(chuàng)建 upload.jsp 文件
頁面的表單應(yīng)該設(shè)為post方式提交抖甘,并且設(shè)置 enctype="multipart/form-data"
${message}為顯示上傳操作結(jié)果通知热鞍。
<body>
<form action="uploadServlet" enctype="multipart/form-data" method="post">
文件上傳支持以下格式:"txt","doc","docx","xls","xlsx","ppt","pdf","xml","html","jpg","png"<br/>
文件上傳:<input type="file" name="file" size="80"/>
<input type="submit" value="提交"><br/>
</form>
<span>${message}</span>
</body>
創(chuàng)建 UploadServlet 類
判斷上傳類型,注意:文件上傳名重復(fù)衔彻,會(huì)覆蓋原有文件薇宠。
存放目錄本例 存放于 "D://workshop//upload_data", 根據(jù)自己情況修改
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
request.setCharacterEncoding("utf-8");
String allowTypes = new String{"txt","doc","docx","xls","xlsx","ppt","pdf","xml","html","jpg","png"};
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// String path = request.getSession().getServletContext().getRealPath("/files");
String path = "D://workshop//upload_data";
System.out.println(path);
try {
List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.isFormField()){
System.out.println("文本信息");
}else{
if (item.getName() != null && !item.getName().equals("")) {
String name = item.getName();
String type = name.substring(name.lastIndexOf('.')+1);
boolean flag = false;
for(String at:allowTypes){
if(at.equals(type)){
flag = true;
}
}
if(flag==false){
System.out.println("文件格式不支持");
request.setAttribute("message", "文件格式不支持");
}else{
int start = name.lastIndexOf("\\");
String filename = name.substring(start+1);
File file = new File(path+"/"+filename);
item.write(file);
request.setAttribute("message", "文件上傳成功");
}
}else{
System.out.println("請選擇待上傳文件");
request.setAttribute("message", "請選擇待上傳文件");
}
}
}
}catch (Exception e) {
e.printStackTrace();
request.setAttribute("message", "文件上傳失敗");
}
request.getRequestDispatcher("upload.jsp").forward(request, response);
}
配置 web.xml
<servlet>
<servlet-name>uploadServlet</servlet-name>
<servlet-class>cn.crabshell.controller.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
測試
啟動(dòng)服務(wù)器后,瀏覽器中輸入:http://localhost:8080/uploadFileDemo/upload.jsp
4.png
選擇文件
5.png
提交
6.png
查看目標(biāo)文件夾
7.png
本例下載 uploadFileDemo.zip