java组件commons-fileupload实现文件上传
时间:2020-10-16 13:02:04|栏目:JAVA代码|点击: 次
一、所需要的包:
1、commons-fileupload-1.2.1.jar:
下载地址
http://commons.apache.org/downloads/download_fileupload.cgi
2、commons-io-1.4.jar:
下载地址
http://commons.apache.org/downloads/download_io.cgi
二、注意事项:
form表单里面要加上enctype="multipart/form-data"
三、代码示例
1、jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>upload</title> </head> <body> <form action="uploadServlet" method="post" enctype="multipart/form-data"> <table> <caption>上传实例</caption> <tr> <td>姓名</td> <td> <input type="text" name="name"> </td> </tr> <tr> <td>年龄</td> <td> <input type="text" name="age"> </td> </tr> <tr> <td>照片</td> <td> <input type="file" name="image"> </td> </tr> <tr> <td></td> <td> <input type="submit" value="提交"> </td> </tr> </table> </form> </body> </html>
2、UploadServlet代码
package servlet; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; /** * 上传servlet * @author lisanlai * */ public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UploadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); // 设置字符编码为UTF-8, 这样支持汉字显示 response.setCharacterEncoding("UTF-8"); Writer o = response.getWriter(); /** * 首先判断form的enctype是不是multipart/form-data * 同时也判断了form的提交方式是不是post * 方法:isMultipartContent(request) */ if(ServletFileUpload.isMultipartContent(request)){ request.setCharacterEncoding("utf-8"); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload DiskFileItemFactory factory = new DiskFileItemFactory(); //设置文件存放的临时文件夹,这个文件夹要真实存在 File fileDir = new File("../webapps/fileupload/tmp/"); if(fileDir.isDirectory() && fileDir.exists()==false){ fileDir.mkdir(); } factory.setRepository(fileDir); //设置最大占用的内存 factory.setSizeThreshold(1024000); //创建ServletFileUpload对象 ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setHeaderEncoding("utf-8"); //设置单个文件最大值byte sfu.setFileSizeMax(102400000); //所有上传文件的总和最大值byte sfu.setSizeMax(204800000); List<FileItem> items = null; try { items = sfu.parseRequest(request); }catch (SizeLimitExceededException e) { System.out.println("文件大小超过了最大值"); } catch(FileUploadException e) { e.printStackTrace(); } //取得items的迭代器 Iterator<FileItem> iter = items==null?null:items.iterator(); //图片上传后存放的路径目录 File images = new File("D:/upload/images/"); if(images.exists()==false){ images.mkdirs(); } //迭代items while(iter!=null && iter.hasNext()){ FileItem item = (FileItem) iter.next(); //如果传过来的是普通的表单域 if(item.isFormField()){ System.out.print("普通的表单域:"); System.out.print(new String(item.getFieldName()) + " "); System.out.println(new String(item.getString("UTF-8"))); } //文件域 else if(!item.isFormField()){ System.out.println("源图片:" + item.getName()); String fileName = item.getName().substring(item.getName().lastIndexOf("\\")); BufferedInputStream in = new BufferedInputStream(item.getInputStream()); //文件存储在D:/upload/images目录下,这个目录也得存在 BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(new File(images.getAbsolutePath()+ fileName))); Streams.copy(in, out, true); o.write("文件上传成功"); } } }else { System.out.println("表单的enctype 类型错误"); } } }
3、web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>UploadTest</display-name> <welcome-file-list> <welcome-file>upload.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>UploadServlet</display-name> <servlet-name>UploadServlet</servlet-name> <servlet-class>servlet.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/uploadServlet</url-pattern> </servlet-mapping> </web-app>
本文已被整理到了《Java上传操作技巧汇总》,欢迎大家学习阅读。
上一篇:java合并多个文件的实例代码
栏 目:JAVA代码
下一篇:Java多线程 线程同步与死锁
本文标题:java组件commons-fileupload实现文件上传
本文地址:http://www.codeinn.net/misctech/12386.html
阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机