使用form表达上传文件(二) 你的名字 2022-05-25 05:21 109阅读 0赞 之前写过同样的文章,但是那一篇不是特别完整,故在这里又写一遍,做一个小小的记录 首先声明,我是通过jsp总的jsp和Servlet实现的文件上传 一。首先新建一个web应用程序 1.准备jar包 commons-fileupload-1.3.jar commons-io-1.4.jar commons-logging-1.2.jar 我主要用到了这三个jar包 二。我先新建一个jsp, 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>文件上传学习jsp</title> </head> <body> <div>这是文件上传页面第二次练习</div> <div style="height: 400px; border: 2px solid red; margin: 50px auto;"> <form method="post" action="upload02.do" enctype="multipart/form-data"> <h2>文件上传</h2> 选择文件: <input type="file" name="file"> <button style="display: block; margin-top: 30px;">提交</button> </form> </div> </body> </html> 这里的代码非常简单,就是定义了一个form 使用同步的方式上传文件,form里面包了一个input type="file" 然后这里的 name="file" 不要忘记。 form标签上记得添加 enctype="multipart/form-data" 添加这个的目的是,一会java可以判断来的表单是属于普通输入表单还是 文件上传表单。 三,因为上面form表单中,action=“upload02.do” 故在web.xml 配置相应的servlet ,如下 <?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_3_0.xsd" id="weixin" version="3.0"> <display-name>weixin</display-name> <servlet> <servlet-name>UploadServlet02</servlet-name> <servlet-class>com.unis.test.upload.UploadServlet02</servlet-class> <load-on-startup>10</load-on-startup> </servlet> <servlet-mapping> <servlet-name>UploadServlet02</servlet-name> <url-pattern>/upload02.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> 文中定义了一个类, UploadServlet02 ,并且我在这个类中的init函数中 有一些操作,故设置了 随着tomcat的加载 该 Servlet就会加载。 四。下面是 UploadServlet02 类的内容 package com.unis.test.upload; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; 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.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.chobits.common.FileUtil; import com.sun.istack.internal.logging.Logger; public class UploadServlet02 extends HttpServlet{ Logger logger = Logger.getLogger(UploadServlet02.class); private String tomcatPath = ""; private String webInfoPath = ""; private String uploadFolder = ""; @Override public void init() throws ServletException { webInfoPath = this.getServletContext().getRealPath("WEB-INF"); logger.info("webInfoPath:"+webInfoPath); System.out.println("webInfoPath:"+webInfoPath); if(webInfoPath==null){ String temp = ""; try { temp = this.getServletContext().getResource("/").getPath(); } catch (MalformedURLException e) { e.printStackTrace(); } webInfoPath = temp + File.separator + "WEB-INF"; } System.out.println("最终生成的webInfoPath:"+webInfoPath); if(webInfoPath!=null && !"".equals(webInfoPath)){ File file = new File(webInfoPath); tomcatPath = file.getParentFile().getParentFile().getParentFile().getAbsolutePath(); System.out.println("tomcatPath:"+tomcatPath); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("上传开始"); try { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); response.setContentType("text/html; charset=utf8"); //判断提交过来的表单是否是上传表单 boolean flag = ServletFileUpload.isMultipartContent(request); if(flag){ //构建一个文件上传处理对象 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //定义一个迭代器 Iterator items = null; //解析出表单中提交的文件内容 items = upload.parseRequest(request).iterator(); //创建一个map 用来接收参数 Map<String, String> mapParam = new HashMap<String, String>(); while(items.hasNext()){ FileItem item = (FileItem) items.next(); //判断参数域是普通的表单输入域还是文件上传域,如果是表单输入域则返回true if(!item.isFormField()){ String fileName = item.getName(); if(!checkImage(fileName)){ throw new Exception("该图片不是以jpg或png结尾的,请上传符合条件的图片"); } uploadFolder = tomcatPath + File.separator + "ims_res" + File.separator + "upload_test"; File uploadFolderFile = new File(uploadFolder); if(!uploadFolderFile.exists()){ uploadFolderFile.mkdirs(); } //构建一个文件上传的路径 //先把该图片上传到tomcat的ims_res\\upload_test 文件夹下 String destFilepath = uploadFolder + File.separator + fileName; File destFile = new File(destFilepath); //返回文件的大小,返回字节数 Long fileLength = item.getSize(); //上传文件 item.write(destFile); out.println("文件名为:"+fileName); out.println("问价大小为:"+fileLength); }else{ String name = item.getFieldName(); String value = item.getString(); mapParam.put(name, value); logger.info("name:"+name); logger.info("value:"+value); } } } } catch (Exception e) { e.printStackTrace(); } } private boolean checkImage(String fileName){ return fileName.endsWith(".jpg") || fileName.endsWith(".png"); } } 在该Servlet中,init函数中是为了 找到tomcat文件夹的根目录, 因为要上传的图片我要放到tomcat 目录中 ,与webapps目录同级我要新建一个文件夹 ims\_res ,然后在此文件夹下新建一个 upload\_test 目录,要上传的文件都放在这里 在doPost方法中 是真正执行 上传操作的代码。利用了 java 的 DiskFileItemFactory 类来 上传,具体代码 仔细看吧。 亲测可以用,但是不支持多张图片的上传。对了,这里 我上传的是图片,因为在代码里,我做了扩展名的限制, 支持 .jpg 和 .png 的图片上传。 不积跬步,无以至千里 不积小流,无以成江海
还没有评论,来说两句吧...