使用ServletFileUpload实现上传
来源:互联网 发布:孕妇必知的民间禁忌 编辑:程序博客网 时间:2024/05/22 03:27
commons-io下载地址:http://commons.apache.org/io/download_io.cgi
最近项目中遇到要提交文件并且提交form中的诸如<input type=text id="height" name="height" value="">之类的参数,一开始一直遇到怎么也获取不到值的情况,比如用request.getAttribute("height")之类的,后来查了文档才知道不能这么用的。需要用循环fileList才可以取到form中提交的属性,以下是代码
common-fileupload组件是apache的一个开源项目之一,可以从http://jakarta.apache.org/commons/fileupload/下载
<%@ 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>Insert title here</title></head><script type="text/javascript">function sc(){sub.submit();}</script><body><form action="/tests/servlet/inputTestServlet" id="sub" method="POST" enctype="multipart/form-data"><input type="file" name="file" id="file" /> <input type="button" name="inp" id="inp" value="上传" onclick="sc();"></form></body></html>
package com.input;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.Iterator;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.FileItemFactory;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class InputTestServlet extends HttpServlet{public InputTestServlet() {super();}public void destroy() {super.destroy();}public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //判断提交过来的表单是否为文件上传菜单 boolean isMultipart= ServletFileUpload.isMultipartContent(request); if(isMultipart){ //构造一个文件上传处理对象 FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8");//解决http报头乱码,即中文文件名乱码 Iterator items; try{ //解析表单中提交的所有文件内容 items=upload.parseRequest(request).iterator(); while(items.hasNext()){ FileItem item = (FileItem) items.next(); if(!item.isFormField()){ //取出上传文件的文件名称 String name = item.getName(); //取得上传文件以后的存储路径 String fileName=name.substring(name.lastIndexOf('\\')+1,name.length()); //上传文件以后的存储路径 String path= request.getSession().getServletContext().getRealPath("/")+fileName; //上传文件 File uploaderFile = new File(path); item.getString("UTF-8"); //解决表单输入输乱码。 item.write(uploaderFile); //打印上传成功信息 response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print("<font size='2'>上传文件为:"+name+"<br>保存的地址为"+path+ "</font>"); } } }catch(Exception e){ e.printStackTrace(); } }}public void init() throws ServletException {}}
最近项目中遇到要提交文件并且提交form中的诸如<input type=text id="height" name="height" value="">之类的参数,一开始一直遇到怎么也获取不到值的情况,比如用request.getAttribute("height")之类的,后来查了文档才知道不能这么用的。需要用循环fileList才可以取到form中提交的属性,以下是代码
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final long MAX_SIZE = 3 * 1024 * 1024;// 设置上传文件最大为 3M // 允许上传的文件格式的列表 final String[] allowedExt = new String[] { "jpg", "jpeg", "gif","png" }; response.setContentType("text/html"); // 设置字符编码为UTF-8, 这样支持汉字显示 // response.setCharacterEncoding("GBK"); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload DiskFileItemFactory dfif = new DiskFileItemFactory(); dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘 dfif.setRepository(new File(request.getRealPath("/") + "ImagesUploadTemp"));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录 // 用以上工厂实例化上传组件 ServletFileUpload sfu = new ServletFileUpload(dfif); // 设置最大上传尺寸 sfu.setSizeMax(MAX_SIZE); PrintWriter out = response.getWriter(); // 从request得到 所有 上传域的列表 List fileList = null; try { fileList = sfu.parseRequest(request); } catch (FileUploadException e) {// 处理文件尺寸过大异常 if (e instanceof SizeLimitExceededException) { out.print("<script>alert('文件尺寸超过规定大小:" + MAX_SIZE + "字节');history.back();</script>"); return; } e.printStackTrace(); } // 没有文件上传 if (fileList == null || fileList.size() == 0) { out.print("<script>alert('请选择上传文件!');history.back();</script>"); return; } HashMap<String, String> paramMap = new HashMap<String, String>(); // 得到所有上传的文件 Iterator fileItr = fileList.iterator(); // 循环处理所有文件 FileItem fileUp= null; String path = null; while (fileItr.hasNext()) { FileItem fileItem = null; long size = 0; // 得到当前文件 fileItem = (FileItem) fileItr.next(); // 忽略简单form字段而不是上传域的文件域(<input type="text" />等) if (fileItem == null || fileItem.isFormField()) { String formname=fileItem.getFieldName();//获取form中的名字 String formcontent=fileItem.getString(); formname=new String(formname.getBytes(),"GBK"); formcontent=new String(formcontent.getBytes(),"GBK"); paramMap.put(formname, formcontent); } else{ //得到放文件的item fileUp= fileItem; // 得到文件的完整路径 path = fileItem.getName(); // 得到文件的大小 size = fileItem.getSize(); if ("".equals(path) || size == 0) { out.print("<script>alert('请选择上传文件!');history.back();</script>"); return; } } } // 得到去除路径的文件名 String t_name = path.substring(path.lastIndexOf("\\") + 1); // 得到文件的扩展名(无扩展名时将得到全名) String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1); // 拒绝接受规定文件格式之外的文件类型 int allowFlag = 0; int allowedExtCount = allowedExt.length; for (; allowFlag < allowedExtCount; allowFlag++) { if (allowedExt[allowFlag].equals(t_ext)) break; } if (allowFlag == allowedExtCount) { StringBuffer sb = new StringBuffer(); for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++) sb.append("*." + allowedExt[allowFlag]); out.println("<script>alert('请上传以下类型的文件" + sb.toString() + "');history.back();</script>"); return; } long now = System.currentTimeMillis(); // 根据系统时间生成上传后保存的文件名 String prefix = String.valueOf(now); // 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下 String u_name = request.getRealPath("/") + "ImagesUploaded/" + prefix + "." + t_ext; // 相对项目路径 String file_url = request.getContextPath() + "/" + "ImagesUploaded/" + prefix + "." + t_ext; try { // 保存文件 fileUp.write(new File(u_name)); out.println("<script type='text/javascript'>parent.KE.plugin[\"image\"].insert('" +paramMap.get("id") + "', '" + file_url + "','" +paramMap.get("imgWidth") + "','" +paramMap.get("imgHeight") + "','" +paramMap.get("imgBorder") + "','" +paramMap.get("imgTitle") + "')</script>"); } catch (Exception e) { e.printStackTrace(); }
0 0
- 使用ServletFileUpload实现上传
- 使用ServletFileUpload实现上传
- 使用ServletFileUpload实现上传
- 使用ServletFileUpload实现上传
- 使用ServletFileUpload 实现文件上传 和获取文件信息
- 使用servletfileupload实现表单文件和数据的一起上传
- Spring Boot使用ServletFileUpload上传文件失败
- 用ServletFileUpload上传图片
- 文件上传和下载-ServletFileUpload
- 文件上传和下载-ServletFileUpload
- ServletFileUpload上传文件带进度条
- 文件上传和下载-ServletFileUpload
- 【ServletFileUpLoad】上传本地文件到服务器
- ServletFileUpload
- 文件上传和下载-ServletFileUpload and DiskFileItemFactory
- 文件上传组件File,DiskFileItemFactory ,ServletFileUpload ,FileItem
- struts2 文件上传 和 ServletFileUpload的矛盾
- 文件上传组件File,DiskFileItemFactory ,ServletFileUpload ,FileItem
- 按位与、或、异或等运算方法
- 微信分享api一次发送多张图片到朋友圈
- ANDROID的APN设置
- Android_adb使用
- AM335X工控应用网络扩展技术详解-DM9000C
- 使用ServletFileUpload实现上传
- Manifest.permission_group权限组
- 织梦仿站系列教程第十讲——通用头部(六)搜索框
- “未能加载文件或程序集“AspNetPager”或它的某一个依赖项。系统找不到指定的路径。”的解决方法
- Eclipse get/set方法自动加上字段注释
- Path Sum II
- ANDROID自定义输入法-自定义键盘
- href&src相对路径表示
- 飘逸的python - 一个极简的event系统