Servlet上传文件源码

来源:互联网 发布:win7 版 人工智能 编辑:程序博客网 时间:2024/06/03 12:34

参考自《Java Web整合开发王者归来》。

这里使用的是Apache Commons Fileupload类库,使用commons-fileupload-1.3.1.jar。


前提:

采用post方式;
需要设置form的enctype属性为multipart/form-data;
由于上传文件较大,需要设置该参数指定浏览器使用二进制上传。如果不设置,enctype默认为applicaton/x-www-form-urlencoded,浏览器将使用ASCII向服务器发送数据,导致文件发送失败。


html代码:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>文件上传</title></head><body><form action="servlet/UploadServlet" method="post" enctype="multipart/form-data"><div align="center"><br/><fieldset style="width: 80%;"><legend>上传文件</legend><br /><div class="line"><div align="left" class="leftDiv">上传文件1</div><div align="left" class="rightDiv"><input type="file" name="file1" class="text" /></div></div><div class="line"><div align="left" class="leftDiv">上传文件2</div><div align="left" class="rightDiv"><input type="file" name="file2" class="text" /></div></div><div class="line"><div align="left" class="leftDiv">上传文件说明1</div><div align="left" class="rightDiv"><input type="text" name="description1" class="text" /></div></div><div class="line"><div align="left" class="leftDiv">上传文件说明2</div><div align="left" class="rightDiv"><input type="text" name="description2" class="text" /></div></div><div class="line"><div align="left" class="leftDiv"></div><div align="left" class="rightDiv"><br><input type="submit" value="上传文件" class="button" /></div></div></fieldset></div></form></body></html>

Servlet后台代码:

package com.ice.servlet;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.annotation.MultipartConfig;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.Part;import org.apache.catalina.core.ApplicationPart;import org.apache.commons.fileupload.DiskFileUpload;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.lang.StringUtils;import org.apache.jasper.tagplugins.jstl.core.Out;import com.sun.corba.se.impl.orbutil.closure.Constant;/** * Servlet implementation class UploadServlet */public class UploadServlet extends HttpServlet {private static final long serialVersionUID = 1L;File tempFile;           /**     * @see HttpServlet#HttpServlet()     */    public UploadServlet() {        super();        // TODO Auto-generated constructor stub    }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);response.setCharacterEncoding("utf-8");//设置输出编码response.getWriter().println("请以POST方式上传文件");}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */@SuppressWarnings("unchecked")  //消除unchecked warningprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");//PrintWriter out = response.getWriter();//String path = this.getServletContext().getRealPath("/");//Part p = request.getPart("file1");//if (p.getContentType().contains("image")) {//ApplicationPart apPart = (ApplicationPart)p;//String fileName = apPart.getFilename();//int path_idx = fileName.lastIndexOf("\\") + 1;//String fileName2 = fileName.substring(path_idx, fileName.length());//p.write(path + "/upload/" + fileName2);//out.write("文件上传成功");////}else {//out.write("请选择图片文件!");//}File file1 = null;File file2 = null;String description1 = null,description2 = null;//DiskFileUpload diskFileUpload = new DiskFileUpload();//DiskFileUpload已经被标记为丢弃方法PrintWriter out = response.getWriter();DiskFileItemFactory factory = new DiskFileItemFactory();factory.setSizeThreshold(4096);//缓冲区大小factory.setRepository(tempFile);//缓冲区目录ServletFileUpload upload = new ServletFileUpload(factory);upload.setSizeMax(4194304);//最大文件尺寸try {List<FileItem> list = upload.parseRequest(request);out.println("遍历所有FileItem...<br/>");for (FileItem fileItem : list) {if (fileItem.isFormField()) {//判断该表单项是否是普通类型,文本域if ("description1".equals(fileItem.getFieldName())) {out.println("遍历到description1...<br/>");description1 = new String(fileItem.getString().getBytes(),"utf-8");}if ("description2".equals(fileItem.getFieldName())) {out.println("遍历到description2...<br/>");description2 = new String(fileItem.getString().getBytes(), "utf-8");}}else {//文件域if ("file1".equals(fileItem.getFieldName())) {File remoteFile = new File(new String(fileItem.getName().getBytes(),"utf-8"));out.println("遍历到file1...<br/>");out.println("客户端文件位置:" + remoteFile.getAbsolutePath() + "<br/>");file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());boolean isExist = file1.getParentFile().mkdirs();//创建文件夹路径file1.createNewFile();//创建新文件InputStream inputStream = fileItem.getInputStream();OutputStream outputStream = new FileOutputStream(file1);//输出到文件中try {byte[] buffer = new byte[1024];//字节缓存int length = 0;while((length = inputStream.read(buffer)) > -1){outputStream.write(buffer, 0, length);//循环读入缓存}out.println("已保存文件:" + file1.getAbsolutePath() + "<br/>");} catch (Exception e) {// TODO: handle exception}finally{outputStream.close();inputStream.close();}}if ("file2".equals(fileItem.getFieldName()) && StringUtils.isNotEmpty(fileItem.getName())) {File remoteFile = new File(new String(fileItem.getName().getBytes(),"utf-8"));out.println("遍历到file2...<br/>");out.println("客户端文件位置:" + remoteFile.getAbsolutePath() + "<br/>");file2 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());file2.getParentFile().mkdirs();//创建文件夹路径file2.createNewFile();//创建新文件InputStream inputStream = fileItem.getInputStream();OutputStream outputStream = new FileOutputStream(file2);//输出到文件中try {byte[] buffer = new byte[1024];//字节缓存int length = 0;while((length = inputStream.read(buffer)) > -1){outputStream.write(buffer, 0, length);//循环读入缓存}out.println("已保存文件:" + file2.getAbsolutePath() + "<br/>");} catch (Exception e) {// TODO: handle exception}finally{outputStream.close();inputStream.close();}}}}out.println("Request 解析完毕!");} catch (Exception e) {e.printStackTrace();}if (file1 != null) {out.println("<div class='line'>");out.println("<div align='left' class='leftDiv'>file1:</div>");out.println("<div align='left' class='rightDiv'>");out.println("<a href='" + request.getContextPath() + "/attachment/" + new String(file1.getName().getBytes(), "utf-8") + "' target=_blank>" + file1.getName() + "</a>");out.println("</div>");out.println("</div>");}if (file2 != null) {out.println("<div class='line'>");out.println("<div align='left' class='leftDiv'>file2:</div>");out.println("<div align='left' class='rightDiv'>");out.println("<a href='" + request.getContextPath() + "/attachment/" + file2.getName() + "' target=_blank>" + file2.getName() + "</a>");out.println("</div>");out.println("</div>");}out.println("<div class='line'>");out.println("<div align='left' class='leftDiv'>description1:</div>");out.println("<div align='left' class='leftDiv'>");out.println(description1);out.println("</div>");out.println("</div>");out.println("<div class='line'>");out.println("<div align='left' class='leftDiv'>description1:</div>");out.println("<div align='left' class='leftDiv'>");out.println(description2);out.println("</div>");out.println("</div>");}}

web.xml中配置:

  <servlet>    <servlet-name>UploadServlet</servlet-name>    <servlet-class>com.ice.servlet.UploadServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>UploadServlet</servlet-name>    <url-pattern>/servlet/UploadServlet</url-pattern>  </servlet-mapping>

附上结果:



以上。

原创粉丝点击