欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSP的文件上传

程序员文章站 2022-06-03 09:06:37
...

jsp页面使用form 标签一起使用来允许用户上传文件到服务器。上传的文件可以是文本文件或图像文件或任何文档。

1.需要用到的jar包

    需要用到的jar包:commons-fileupload-1.3.2.jar,commons-io-2.5.jar

    为大家准备好的jar包链接:https://pan.baidu.com/s/1GyOp2o0ID-4JeMNW1YSMrw 密码:tm8g

2.注意事项

    1)表单 method 属性应该设置为 POST 方法,不能使用 GET 方法。

    2)表单 enctype 属性应该设置为 multipart/form-data

    3)表单 enctype 属性设置为 multipart/form-data后,后台servlet接收表单中的数据时会接收不到。

        解决方法一:用JavaScript重新url

    //先获取form表单的action属性
    var action = $form.attr("action");
    action = action + "?studentName=" + $("#studentName").val() + "&studentID" + $("#studentID").val();
    $form.attr("action",action);
    $form.submit();

        注意中文乱码处理!!

        解决方法二:像我这样写。

3.上代码
例:首先创建两个jsp页面,一个servlet负责后台操作

   index页面代码:

<%@ 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="<%=basePath%>">

<title>文件上传</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">
</head>

<body>
	<h3>文件上传</h3>
	<form method="post" action="servlet/UploadServlet" enctype="multipart/form-data">
		<label>姓名:</label><input name="studentName" type="text"/><br>
		<label>学号:</label><input name="studentID" type="text" /><br>
		<label>选择一个照片: </label><input type="file" name="studentImg" /> <br>
		<input type="submit" value="上传" />
	</form>
</body>
</html>

    message页面代码,负责展示上传的信息

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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="<%=basePath%>">
    
    <title>消息</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="styles.css">
	-->

  </head>
  
  <body>
  	<c:choose>
  		<c:when test="${!empty student}">
  			<table>
  				<tr>
  					<td>姓名:</td>
  					<td>${student.name}</td>
  				</tr>
  				<tr>
  					<td>学号:</td>
  					<td>${student.id}</td>
  				</tr>
  				<tr>
  					<td>照片:</td>
  					<td><img src="${student.img}" /></td>
  				</tr>
  			</table>
  		</c:when>
  		<c:otherwise>
  			<h3 style="text-align: center; color: red;">失败,没有任何信息</h3>
  		</c:otherwise>
  	</c:choose>
  </body>
</html>

后台的servlet

package top.liu15.controller;

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 top.liu15.entity.Student;

public class UploadServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = -7106039161860356768L;

    /**
     * Constructor of the object.
     */
    public UploadServlet() {
        super();
    }
    // 上传文件存储目录
    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
    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检测是否为多媒体上传
        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();
        }
        //存放学生数据
        Student stu = null;
        try {
            // 解析请求的内容提取文件数据
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                stu =  new Student();
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        stu.setImg(request.getContextPath() + "/" + UPLOAD_DIRECTORY + "/" + fileName);
                        // 保存文件到硬盘
                        item.write(storeFile);
                        //判断字段名
                    } else{
                        //字段名
                        String name = item.getFieldName();
                        //对应的值
                        String value = new String(item.get(),"utf-8");
                        if("studentName".equals(name)){
                            stu.setName(value);
                        }else{
                            stu.setId(value);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message","错误信息: " + ex.getMessage());
        }
        request.setAttribute("student", stu);
        // 跳转到 message.jsp
        getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}


运行结果如下:

    index.jsp页面

JSP的文件上传

    message页面

   JSP的文件上传


希望本篇文章可以帮助到您!


相关标签: jsp java