java 简单实现上传 | commons-fileupload

使用servlet来实现

配置pom.xml <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency>

servlet protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建一个文件处理工厂 FileItemFactory factory= new DiskFileItemFactory(); //创建一个存放临时中转的仓库 ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.temdir"); ((DiskFileItemFactory) factory).setRepository(repository); //创建一个处理上传的处理器 ServletFileUpload upload = new ServletFileUpload(factory); try { //获取从表单提交上来的数据,从表单上传的数据会自动被分割,比如一个input:text,input:file,就会被分成两个item List items = upload.parseRequest(req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); //检查是否是文件 if(item.isFormField()) { //如果不是文件d String name = item.getFieldName(); String value =item.getString(); System.out.println(name+":"+value); }else { //如果是文件 String fieldName = item.getFieldName(); //这个fileName是上传文件名 String fileName = item.getName(); System.out.println(fieldName+":"+fileName); //新建一个文件,用于存储上传的文件 File uploadFile = new File("D:\\",fileName); item.write(uploadFile); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }

在web.xml中配置好servlet

前端页面

<form action="/swfupload/fupload" enctype="multipart/form-data" method="post"></form>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzpfgf.html