JSP&Struts2----文件上传

以下罗列了简单的三种基于Apache的commons-fileupload上传方式

============================================

所需jar包:

commons-fileupload-1.1.1.jar

commons-io-1.2.jar


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.*;
import java.util.*;
import java.util.regex.*;
import java.io.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;


public class FileUpload extends HttpServlet { 


@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
}


private ServletConfig config = null;




private File tempPath = new File("D:\\upload\\temp\\"); // 用于存放临时文件的目录


public void destroy() {
config = null;
super.destroy();
}



public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
int id = -1;

String uploadPath = config.getInitParameter("uploadPath"); // 用于存放上传文件的目录

res.setContentType("text/html; charset=GB2312");
PrintWriter out = res.getWriter();
System.out.println(req.getContentLength());
System.out.println(req.getContentType());
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(4096);
// the location for saving data that is larger than getSizeThreshold()
factory.setRepository(tempPath);


ServletFileUpload upload = new ServletFileUpload(factory);
// maximum size before a FileUploadException will be thrown
upload.setSizeMax(1000000);
try {
List fileItems = upload.parseRequest(req);
// assume we know there are two files. The first file is a small
// text file, the second is unknown and is written to a file on
// the server
Iterator iter = fileItems.iterator();


// 正则匹配,过滤路径取文件名
String regExp = ".+\\\\(.+)$";


// 过滤掉的文件类型
String[] errorType = { ".exe", ".com", ".cgi", ".jsp" };
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(item.isFormField()) {
//getFieldName() ----get form field param
if(item.getFieldName().equals("id")) {
id = Integer.parseInt(item.getString());
}
}
// 忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result) {
for (int temp = 0; temp < errorType.length; temp++) {
if (m.group(1).endsWith(errorType[temp])) {
throw new IOException(name + ": wrong type");
}
}
try {


// 保存上传的文件到指定的目录


// 在下文中上传文件至数据库时,将对这里改写
item.write(new File(uploadPath + id + ".jpg"));


out.print(name + "&nbsp;&nbsp;" + size + "<br>");
} catch (Exception e) {
out.println(e);
}


} else {
throw new IOException("fail to upload");
}
}
}
} catch (IOException e) {
out.println(e);
} catch (FileUploadException e) {
out.println(e);
}


}

}


----web.xml


<?xml version="1.0" encoding="UTF-8"?>


<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>upload a file to server</description>
<display-name>FileUpload</display-name>
<servlet-name>FileUpload</servlet-name>
<servlet-class>
com.shopping.util.servlet.FileUpload
</servlet-class>
<init-param>
<param-name>uploadPath</param-name>
<param-value>
D:\\share\\JavaProjects\\Shopping\\WebRoot\\images\\product\\
</param-value>
</init-param>
</servlet>

----Web3.0之后基于注解的文件上传


1、Servlet 3.0 对文件上传的支持(源自:http://blog.csdn.net/qq_35928356/article/details/72954893)

Servlet 3.0 改进了部分API,使得Java web 的开发进一步得到简化。 
其中两个较大的改进是:

  • HttpServletRequest 增加了对文件上传的支持
  • ServletContext 允许通过编程的方式动态注册Servlet、Filter

HttpServletRequest 提供了如下两个方法来处理文件上传 :

  • Part getPart(String name) : 根据文件上传域name属性来获取上传文件。
  • Collection< Part > getParts() :获取所有的文件上传域。

官方文档对这两个方法的说明为: 
这里写图片描述
这里写图片描述

上面两个方法的返回值都涉及一个API :Part ;每个Part对象对应于一个文件上传域,该对象提供了大量方法来访问上传的文件,如文件类型、大小等。并提供了一个write(String name)将文件写入服务器硬盘。

上传文件表单 : 
为了向服务器上传文件,需要在表单里使用 < input type=”file” name=”xxx” …./>文件域,这个文件域会在HTML页面生成一个单行文本框和一个用于“浏览文件”的button。除此之外,表单必须设置enctype属性 
enctype属性指定的是表单数据的编码方式,该属性有如下三个值:

  • application/x-www-form-urlencoded :这是默认的编码方式,他只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成URL编码方式
  • multipart/form-data : 这种方式会以二进制流的方式来处理表单数据,这种编码方式会把 文件域指定文件的内容 (并不是原文件,而是文件内容)也封装到请求参数里
  • text/plain : 这种编码方式当表单的action 属性为 mailto:URL 时比较方便,主要用于直接通过表单发送邮件

如果将enctype设置为 application/x-www-form-urlencoded ,或者不设置enctype属性,提交表单时只会发送文件域文本框里的字符串,也就是浏览者所选择文件的绝对路径。这对服务器来说没多大用处,毕竟服务器又无法访问客户机的文件系统。

Servlet实现文件上传代码:

使用Servlet实现文件上传非常简单,不需要commons-fileupload 等工具。注意导入servlet-api.jar 
表单示例:

    <form action="upload" method="post" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit" value="submit">
    </form>
 
 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

Servlet示例:

/**@MultipartConfig
 * 不指定location属性时,在IDEA环境下,part.write(fileName);上传文件默认保存到以下地址
 *      C:\Users\Windward\.IntelliJIdea2017.1\system\tomcat\index_jsp_upLoad\work\Catalina\localhost\ROOT下
 * 指定location属性,需要手动创建文件夹
 * 1.相对路径时:如 location = "/uploadFiles"
 *  保存地址为:E:\apache-tomcat-8.0.24\work\Catalina\localhost\upLoad_war_exploded\uploadFiles
 * 2.绝对路径时:如 location = "F:\\uploadFiles"
 *  保存至绝对路径下,如 F:\uploadFiles下
 *
 */
@javax.servlet.annotation.MultipartConfig(location = "F:\\uploadFiles")
@javax.servlet.annotation.WebServlet(name = "upload",urlPatterns={"/upload"})
public class UploadServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        //设置请求的编码方式
        request.setCharacterEncoding("utf-8");
        //设置响应内容,与编码
        response.setContentType("text/html;charset=utf-8");
        //获取输出流,输出到客户端浏览器
        PrintWriter out = response.getWriter();
        //获取文件上传域 "file"域,Part对象封装了获取的文件
        Part part = request.getPart("file");
        //获取文件类型
        String fileType = part.getContentType();
        //获取文件大小
        Long size= part.getSize();
        //获取文件上传域的所有headerName
        Collection<String> headerNames = part.getHeaderNames();
        //获取包含原始文件名的字符串
        String fileNameInfo = part.getHeader("content-disposition");
        //提取上传文件的原始文件名
        String fileName = fileNameInfo.substring(fileNameInfo.indexOf("filename=")+10,
                                                    fileNameInfo.length()-1);
       //将文件写入服务器硬盘,存入的文件名为fileName(write的参数),
        // 路径为@MultipartConfig(location = "/uploadFiles")location属性值
        part.write(fileName);

        out.println("<html>");
        out.println("<body>");
        out.print("文件名:"+fileName+"<br/>");
        out.print("文件类型:"+fileType+"<br/>");
        out.print("文件大小(byte):"+size+"<br/>");
        //遍历打印文件上传域的所有 HeaderName-Value
        for (String headerName: headerNames ) {
            out.print("------------------------------------------------------------------"+"<br/>");
            out.print("headerName :"+headerName+"<br/>");
            //输出headerName对应的value值
            out.print("value:"+part.getHeader(headerName) +"<br/>");
            out.print("------------------------------------------------------------------"+"<br/>");
        }
        out.println("</body>");
        out.println("</html>");
        out.close();

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doPost(request,response);
    }
}


----Struts2


package com.struts2.action;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.UUID;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.struts2.service.PicService;


public class AddPicProAction extends ActionSupport {
private String picName;
private File pic;
private String picFileName;
private String picContentType;

public String getPicName() {
return picName;
}
public void setPicName(String picName) {
this.picName = picName;
}
public File getPic() {
return pic;
}
public void setPic(File pic) {
this.pic = pic;
}
public String getPicFileName() {
return picFileName;
}
public void setPicFileName(String picFileName) {
this.picFileName = picFileName;
}
public String getPicContentType() {
return picContentType;
}
public void setPicContentType(String picContentType) {
this.picContentType = picContentType;
}

public String execute() throws Exception{

//以下是我自己测试路径写的,第一个: 绝对路径,第二个: 项目名/upload,第三个: 通过struts.xml配置文件对当前Action的uploadPath参数赋值(注释掉了),其实和servlet一样的
// String uploadPath = 
// ServletActionContext.getServletContext().getRealPath("/upload");
// String uploadPath = ServletActionContext.getServletContext().getContextPath() + "/upload";
// String uploadPath = null;
// ServletActionContext.getRequest().getRealPath(uploadPath);

String uploadPath = "D:\\eclipse-jee-neon-3-win32-x86_64\\workspace\\fileUpload\\WebContent\\upload";
System.out.println(uploadPath);
String newFileName = 
UUID.randomUUID().toString() + picFileName.substring(picFileName.lastIndexOf("."));
FileInputStream fis = new FileInputStream(pic);
FileOutputStream fos = new FileOutputStream(uploadPath + "/" + newFileName);
//System.out.println(uploadPath + "/" + newFileName);
byte[] buff = new byte[1024];
int len = 0;
while((len = fis.read(buff)) > 0){
fos.write(buff, 0, len);
}
fis.close();
fos.close();
PicService ps = new PicService();
ps.addPic(picName , newFileName);
return SUCCESS;
}
}


----struts.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">


<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="default" namespace="/" extends="struts-default">
<action name="addPicPro" 
class="com.struts2.action.AddPicProAction">
<!-- <param name="uploadPath">D:\\eclipse-jee-neon-3-win32-x86_64\\workspace\\fileUpload\\WebContent\\upload</param>
 --> <interceptor-ref name="fileUpload">
<param name="allowedTypes">image/jpeg,image/png</param>
<param name="maximumSize">200000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result type="chain">listPics</result>
<result name="input">/WEB-INF/content/uploadForm.jsp</result>
</action>

<action name="listPics" 
class="com.struts2.action.ListPicsAction">
<result>/WEB-INF/content/listPics.jsp</result>
</action>

<action name="*">
<result>/WEB-INF/content/{1}.jsp</result>
</action>
</package>

</struts>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值