servlet 表单加上multipart/form-data后request.getParameter获取NULL(已解决)

先上结论(可能不对,因为这是根据实践猜测而来,欢迎指正)

表单改为multipart/form-data传值后,数据就不能通过普通的request.getParameter获取。

文件和文件名通过FileItem对象来获取,普通表单数据其实也包含在内。

先获取所有的items

List<FileItem> formItems = upload.parseRequest(request);

遍历items,Listz中包含表单中所有的input,按你jsp中form表单写的顺序放的

for (FileItem item : formItems)

循环中用到item的三个函数

item.isFormField()//判断本次遍历的item中是普通input控件的还是file控件,即判断type

item.getFieldName()//获取本次遍历的item中input控件的name值,用它结合if判断是否遍历到了自己想要的控件

item.getString()//获取本次遍历的item中input控件传来的值,参数填编码如item.getString("UTF-8"),取值的函数

好了,说完原理,上源码

<form action="Video_RegisterServlet" method="post" enctype="multipart/form-data">
                <dl>
                    <dt>视频描述</dt>
                    <dd class="ipt_box">
                        <input id="usr" name="video_desc" type="text" placeholder="请输入视频描述" />
                    </dd>
                </dl>
                
                <dl>
                    <dt>所属课程</dt>
                    <dd class="ipt_box">
                        <input id="pwd" name="course_name" type="text" placeholder="所属课程" />
                    </dd>
                </dl>
                
                <dl>
                    <dt>文件</dt>
                    <dd class="ipt_box">
                        <input id="pwd" name="v_file" type="file" style="border:0px;"/>
                    </dd>
                </dl>
                
                <dl>
                    <dd class="ipt_reg_box">
                        <input class="regBtn" type="submit" value="上传" style="margin-left:40px;"/>
                    </dd>
                </dl>
            </form>

package com.lxz.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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.lxz.dao.VideoDao;
import com.lxz.viso.Video;

/**
 * Servlet implementation class Video_RegisterServlet
 */
public class Video_RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private static final String UPLOAD_DIRECTORY = "upload";
    
    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
 
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Video_RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        
        
        String video_desc = request.getParameter("video_desc");
        
        String course_name = request.getParameter("course_name");//改了这里
        
        
        if (!ServletFileUpload.isMultipartContent(request)) {
                // 如果不是则停止
                PrintWriter writer = response.getWriter();
                writer.println("Error: 表单必须包含 enctype=multipart/form-data");
                writer.flush();
                return;
         }
        
        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        
        ServletFileUpload upload = new ServletFileUpload(factory);
        
        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);
        
        // 中文处理
        upload.setHeaderEncoding("UTF-8");
        
        String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
        
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        VideoDao videodao = new VideoDao();
        Video video = new Video();
        String filePath;
        File storeFile;
        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
 
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    
                    if(item.getFieldName().equals("video_desc"))//是否遍历到name=video_desc的input
                    video_desc = item.getString("UTF-8");//遍历到了,获取其值
                    
                    if(item.getFieldName().equals("course_name"))
                    course_name = item.getString("UTF-8");
                   
                    if (!item.isFormField()) {//前面有个感叹号
                        String fileName = new File(item.getName()).getName();
                        
                        //检验是否存在相同文件名
                        video.setCourse_name(course_name);
                        video.setVideo_desc(video_desc);
                        video.setVideo_name(fileName);
                        //video.setVideo_path(uploadPath);
                        if(videodao.searchVideos(video))
                        {
                            request.setAttribute("msg", "已存在视频名称");
                            //已存在视频名称
                        }else{
                            videodao.addVideo(video);
                            filePath = uploadPath + File.separator + fileName;
                            storeFile = new File(filePath);
                            // 在控制台输出文件的上传路径
                            System.out.println(filePath);
                            // 保存文件到硬盘
                            item.write(storeFile);
                            request.setAttribute("msg","文件上传成功!");
                        }

}
                }
            }
        } catch (Exception ex) {
            request.setAttribute("msg","错误信息: " + ex.getMessage());
        }
        request.getRequestDispatcher("v_register.jsp").forward(request, response);
        
    }

/**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

上一篇:CENTOS 基础指令——查看系统环境


下一篇:观察者模式(Observer pattern)