servlet3多文件上传_Servlet 3文件上传– @MultipartConfig,部分

servlet3多文件上传

Today we will look into Servlet 3 File Upload Example using @MultipartConfig annotation and javax.servlet.http.Part. Sometime back I wrote an article about Servlet File Upload and I used Apache FileUpload API but here we will use Servlet 3 File Upload feature.

今天,我们将研究使用@MultipartConfig批注和javax.servlet.http.Part Servlet 3文件上传示例。 有时我写了一篇有关Servlet File Upload的文章,我使用了Apache FileUpload API,但是这里我们将使用Servlet 3 File Upload功能。

Servlet 3文件上传 (Servlet 3 File Upload)

Since File Upload is a common task in web applications, Servlet Specs 3.0 provided additional support for uploading files to server and we don’t have to depend on any third party APIs for this. In this tutorial we will see how we can use Servlet 3.0 API for uploading Files to server.

由于文件上载是Web应用程序中的常见任务,因此Servlet Specs 3.0为将文件上载到服务器提供了额外的支持,因此我们不必依赖任何第三方API。 在本教程中,我们将看到如何使用Servlet 3.0 API将文件上传到服务器。

MultipartConfig (MultipartConfig)

We need to annotate File Upload handler servlet with MultipartConfig annotation to handle multipart/form-data requests that is used for uploading file to server. MultipartConfig annotation has following attributes:

我们需要使用MultipartConfig注释对File Upload处理程序Servlet进行注释,以处理用于将文件上传到服务器的multipart / form-data请求。 MultipartConfig批注具有以下属性:

  • fileSizeThreshold: We can specify the size threshold after which the file will be written to disk. The size value is in bytes, so 1024*1024*10 is 10 MB.

    fileSizeThreshold :我们可以指定将文件写入磁盘之后的大小阈值。 大小值以字节为单位,因此1024 * 1024 * 10为10 MB。
  • location: Directory where files will be stored by default, it’s default value is “”.

    location :默认情况下将存储文件的目录,默认值为“”。
  • maxFileSize: Maximum size allowed to upload a file, it’s value is provided in bytes. It’s default value is -1L means unlimited.

    maxFileSize :允许上传文件的最大大小,其值以字节为单位。 默认值为-1L表示无限制。
  • maxRequestSize: Maximum size allowed for multipart/form-data request. Default value is -1L that means unlimited.

    maxRequestSize :多部分/表单数据请求所允许的最大大小。 默认值为-1L,表示无限制。

Read more about annotations at Java Annotations Tutorial.

Java Annotations Tutorial中阅读有关注释的更多信息。

零件界面 (Part Interface)

Part interface represents a part or form item that was received within a multipart/form-data POST request. Some important methods are getInputStream(), write(String fileName) that we can use to read and write file.

零件接口表示在multipart / form-data POST请求中收到的零件或表单项。 一些重要的方法是getInputStream()write(String fileName) ,我们可以使用它们来读写文件。

HttpServletRequest的更改 (HttpServletRequest Changes)

New methods got added in HttpServletRequest to get all the parts in multipart/form-data request through getParts() method. We can get a specific part using getPart(String partName) method.

HttpServletRequest添加了新方法,以通过getParts()方法获取multipart / form-data请求中的所有部分。 我们可以使用getPart(String partName)方法获得特定零件。

Let’s see a simple project where we will use above API methods to upload file using servlet. Our project structure will look like below image.

让我们看一个简单的项目,在该项目中,我们将使用上述API方法来使用servlet上传文件。 我们的项目结构如下图所示。

HTML表格 (HTML Form)

We have a simple html page where we can select the file to upload and submit request to server to get it uploaded.

我们有一个简单的html页面,我们可以在其中选择要上传的文件,然后向服务器提交请求以使其上传。

index.html

index.html

<html>
<head></head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="file" name="fileName">
<br>
<input type="submit" value="Upload">
</form>
</body>
</html>

文件上传Servlet (File Upload Servlet)

Here is our File Upload Servlet implementation.

这是我们的文件上传Servlet实现。

FileUploadServlet.java

FileUploadServlet.java

package com.journaldev.servlet;
 
import java.io.File;
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
 
@WebServlet("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*10, 	// 10 MB 
                 maxFileSize=1024*1024*50,      	// 50 MB
                 maxRequestSize=1024*1024*100)   	// 100 MB
public class FileUploadServlet extends HttpServlet {
 
    private static final long serialVersionUID = 205242440643911308L;
	
    /**
     * Directory where uploaded files will be saved, its relative to
     * the web application directory.
     */
    private static final String UPLOAD_DIR = "uploads";
     
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // gets absolute path of the web application
        String applicationPath = request.getServletContext().getRealPath("");
        // constructs path of the directory to save uploaded file
        String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
         
        // creates the save directory if it does not exists
        File fileSaveDir = new File(uploadFilePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdirs();
        }
        System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());
        
        String fileName = null;
        //Get all the parts from request and write it to the file on server
        for (Part part : request.getParts()) {
            fileName = getFileName(part);
            part.write(uploadFilePath + File.separator + fileName);
        }
 
        request.setAttribute("message", fileName + " File uploaded successfully!");
        getServletContext().getRequestDispatcher("/response.jsp").forward(
                request, response);
    }
 
    /**
     * Utility method to get file name from HTTP header content-disposition
     */
    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        System.out.println("content-disposition header= "+contentDisp);
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf("=") + 2, token.length()-1);
            }
        }
        return "";
    }
}

Notice the use of @MultipartConfig annotation to specify different size parameters for upload file. We need to use request header “content-disposition” attribute to get the file name sent by client, we will save the file with same name.

请注意,使用@MultipartConfig批注为上传文件指定不同的大小参数。 我们需要使用请求标头的“ content-disposition”属性来获取客户端发送的文件名,我们将使用相同的名称保存文件。

The directory location is relative to web application where I am saving the file, you can configure it to some other location like in Apache Commons FileUpload example.

该目录位置是相对于我要将文件保存到的Web应用程序而言的,您可以将其配置为其他位置,例如在Apache Commons FileUpload示例中。

响应JSP (Response JSP)

A simple JSP page that will be sent as response to client once the file is uploaded successfully to server.

成功将文件成功上传到服务器后,将发送一个简单的JSP页面作为对客户端的响应。

response.jsp

response.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Upload File Response</title>
</head>
<body>
	<%-- Using JSP EL to get message attribute value from request scope --%>
    <h2>${requestScope.message}</h2>
</body>
</html>

部署描述符 (Deployment Descriptor)

There is nothing new in web.xml file for servlet file upload, it’s only used to make the index.html as welcome file.

web.xml文件中没有用于servlet文件上传的新内容,仅用于将index.html用作欢迎文件。

web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>ServletFileUploadExample</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

Now when we run the application, we get following pages as response.

现在,当我们运行该应用程序时,我们将获得以下页面作为响应。

The logs will show the directory location where file is saved and content-disposition header information.

日志将显示文件保存的目录位置和内容处置标头信息。

Upload File Directory=/Users/pankaj/Documents/workspace/j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ServletFileUploadExample/uploads
content-disposition header= form-data; name="fileName"; filename="IMG_2046.jpg"

I am running Tomcat through Eclipse, that’s why file location is like this. If you run tomcat through command line and deploy application by exporting as WAR file into webapps directory, you will get different structure but a clear one.

我通过Eclipse运行Tomcat,这就是文件位置是这样的原因。 如果通过命令行运行tomcat并通过将WAR文件导出到webapps目录中来部署应用程序,则会得到不同的结构,但结构很清晰。

翻译自: https://www.journaldev.com/2122/servlet-3-file-upload-multipartconfig-part

servlet3多文件上传

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值