首页 > 代码库 > 上传文件form表单enctype="multipart/form-data"传值解决办法(代原代码)

上传文件form表单enctype="multipart/form-data"传值解决办法(代原代码)

 

最近做的一个项目里遇到一个问 题,就是如何在上传文件的表单里传递其它的变量,因为一但form表单用了enctype="multipart/form-data"类型后,所有的值 都是以二进制进行传递的,所以当我们想取出这个表单里传递过来的其它变量的时候,就会遇到一个问题,那就是用request取不到传递过来的变量。在网上 找了很多资料,也都是大至说一下,在这里我就借花献佛发个完整的原代码解决这个问题!!!

工程目录如下:

上传文件form表单enctype=multipart/form-data传值解决办法(代原代码) - jn1981 - jn1981的个人主页
两个jar可以去apache上下载:
http://commons.apache.org/fileupload/
http://commons.apache.org/io/

四个文件原代码分别为:

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>
   <servlet-name>fileUpload</servlet-name>
   <servlet-class>servlet.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>fileUpload</servlet-name>
   <url-pattern>/fileUpload</url-pattern>
</servlet-mapping>
<filter>
   <filter-name>encodingFilter</filter-name>
   <filter-class>servlet.EncodeFilter</filter-class>
   <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>encodingFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
<!-- clear temporary file when delete the affix ,
   the temporary file path=C:\Program Files\Apache Software Foundation\Tomcat 6.0\temp-->
<listener>
   <listener-class>
    org.apache.commons.fileupload.servlet.FileCleanerCleanup
   </listener-class>
</listener>
<listener>
   <listener-class>
    org.apache.commons.fileupload.servlet.FileCleanerCleanup
   </listener-class>
</listener>
<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
   <base href="http://www.mamicode.com/">

   <title>My JSP ‘index.jsp‘ starting page</title>
   <meta http-equiv="pragma" content="no-cache">
   <meta http-equiv="cache-control" content="no-cache">
   <meta http-equiv="expires" content="0">
   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
   <meta http-equiv="description" content="This is my page">
   <!--
<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/styles.css">
-->
</head>

<body>
   <form action="<%=path %>/fileUpload" method="post" enctype="multipart/form-data">
    文件:
    <input type="file" name="file">
    姓名:
    <input name="name" />
    <input type="hidden" name="add" value="http://www.mamicode.com/深圳"/>
    <input type="submit">
   </form>
</body>
</html>


success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="http://www.mamicode.com/">
   
    <title>My JSP ‘success.jsp‘ starting page</title>
   
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<!--
<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/styles.css">
-->

</head>

<body>
user.name=${user.name}<br>
user.add=${user.add}<br>
    file:=<a href="http://www.mamicode.com/${affix.affixUrl}">${affix.affixName}</a>
</body>
</html>


Affix.java


package model;

import java.util.Date;

public class Affix {

    private String tableName;

    private Long tableRecordId;

    private String affixName;

    private String affixUrl;

    private long size;

    private long creatorId;

    private Date createDate;

    private Long updaterId;

    private Date updatorDate;

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public Long getTableRecordId() {
        return tableRecordId;
    }

    public void setTableRecordId(Long tableRecordId) {
        this.tableRecordId = tableRecordId;
    }

    public String getAffixName() {
        return affixName;
    }

    public void setAffixName(String affixName) {
        this.affixName = affixName;
    }

    public String getAffixUrl() {
        return affixUrl;
    }

    public void setAffixUrl(String affixUrl) {
        this.affixUrl = affixUrl;
    }

    public long getSize() {
        return size;
    }

    public void setSize(long l) {
        this.size = l;
    }

    public long getCreatorId() {
        return creatorId;
    }

    public void setCreatorId(long creatorId) {
        this.creatorId = creatorId;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Long getUpdaterId() {
        return updaterId;
    }

    public void setUpdaterId(Long updaterId) {
        this.updaterId = updaterId;
    }

    public Date getUpdatorDate() {
        return updatorDate;
    }

    public void setUpdatorDate(Date updatorDate) {
        this.updatorDate = updatorDate;
    }

}

User.java

package model;

public class User {

    private String name;

    private String add;

    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAdd() {
        return add;
    }

    public void setAdd(String add) {
        this.add = add;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int i) {
        this.age = i;
    }

}

EncodeFilter.java


package servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


public class EncodeFilter implements Filter {

    private String encoding = null;

    public void destroy() {
        encoding = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException {
        if (encoding != null)
            request.setCharacterEncoding(encoding);
        filterChain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
    }

}

FileUpload.java


package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
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 model.Affix;
import model.User;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class FileUpload extends HttpServlet {

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String tempPath = "d:\\file\\";
        File file = new File(tempPath);
        if(!file.exists()){
            file.mkdir();
        }
  
        System.out.println(ServletFileUpload.isMultipartContent(request));
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // upload.setSizeMax(1024 * 1024 * 50L);
        // Parse the request
        List items = null;
        try {
           
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte data[] = new byte[1024];
        int i = 0;
        Affix affix = null;
        User user = new User();
        if (items != null)
            for (Iterator iterator = items.iterator(); iterator.hasNext();) {
                FileItem item = (FileItem) iterator.next();
               
                if (item.isFormField()) {
                    System.out.print(new String(item.getString("UTF-8")));
                    if ("add".equals(item.getFieldName())) {
                        user.setAdd(new String(item.getString("UTF-8")));
                    } else if ("name".equals(item.getFieldName())) {
                        user.setName(new String(item.getString("UTF-8")));
                    } else if ("age".equals(item.getFieldName())) {
                        user.setAge(Integer.parseInt(item.getString()));
                    }
                 
                    // BeanUtils.setFieldValue(user, item.getFieldName(), item
                    // .getString());
              
                } else {
                    String fileName = item.getName().substring(
                            item.getName().lastIndexOf(File.separator) + 1,
                            item.getName().length());
                    InputStream inputStream = item.getInputStream();
                    // InputStream inputStream = request.getInputStream();
                    OutputStream outputStream = new FileOutputStream(tempPath
                            + fileName);
                    while ((i = inputStream.read(data)) != -1) {
                        outputStream.write(data, 0, i);
                    }
                    inputStream.close();
                    outputStream.close();
                    affix = new Affix();
                    affix.setCreateDate(new Date());
                    affix.setTableName("t_test_user");
                    affix.setSize(item.getSize());
                    affix.setAffixUrl(tempPath + fileName);
                    affix.setAffixName(fileName);
                }
            }
     
        // userService.addUser(user);
        // fileService.addFile(file)
        request.setAttribute("user", user);
        request.setAttribute("affix", affix);
        request.getRequestDispatcher("/success.jsp").forward(request, response);
        // response.sendRedirect("success.jsp");
    }
}

代码有点乱,工作有点忙在这里就不改了。

执行结果如图:

 

上传文件form表单enctype=multipart/form-data传值解决办法(代原代码) - jn1981 - jn1981的个人主页
 
上传文件form表单enctype=multipart/form-data传值解决办法(代原代码) - jn1981 - jn1981的个人主页
 

 

 

 

上传文件form表单enctype="multipart/form-data"传值解决办法(代原代码)