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 MBmaxRequestSize=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 applicationString applicationPath = request.getServletContext().getRealPath("");// constructs path of the directory to save uploaded fileString uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;// creates the save directory if it does not existsFile 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 serverfor (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目录中来部署应用程序,则会得到不同的结构,但结构很清晰。

Download Servlet 3 Multipart File Upload Project下载Servlet 3多部分文件上传项目

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

servlet3多文件上传

servlet3多文件上传_Servlet 3文件上传– @MultipartConfig,部分相关推荐

  1. springmvc与Servlet3.0不依赖common包实现文件上传

    Servlet3.0以上的版本不再需要第三方组件Commons.io和commons-fileupload,可以使用@MultipartConfig注解在Servlet上进行配置上传,也可以在web. ...

  2. Java Servlet3.0使用getPart/getParts实现单文件和多文件上传

    一.使用工具: (1)Firefox浏览器 (2)Eclipse 二.实现单文件上传 (1)Servlet 源码 package com.servlet;import java.io.IOExcept ...

  3. 学习日志day41(2021-09-03)(1、文件的上传 2、文件的查看 3、文件的下载 4、使用工具类上传文件 5、基于servlet3.0以上的文件上传 )

    学习内容:学习JavaWeb(Day41) 1.文件的上传 2.文件的查看 3.文件的下载 4.使用工具类上传文件 5.基于servlet3.0以上的文件上传 1.文件的上传 (1)实现文件的上传需要 ...

  4. Python监控目录文件夹,并使用SFTP上传目录及文件到linux服务器

    Python 扫描监控本地文件夹并进行超大文件上传 方案1:WebUploader大文件分块多线程并发上传 方案2:watchdog目录文件夹监控,paramiko STFP上传服务器 方案3:优化2 ...

  5. ASP.NET,IIS7.0 上传大视频文件报错

    一.问题概述: 最近开发上传视频文件的功能.基本流程已经跑通了,可是上传30M以上的文件时就会报错. 二.资料海洋瞎扑腾 从网上查了一些资料,一般都是下面这种说法: 看着步骤倒是也不算繁琐,可是本人照 ...

  6. JSP中的文件操作:数据流、File类、文件浏览、目录操作、上传下载

    ​ 文件可以永久地存储信息,从本质上讲文件就是存放在盘上的一系列数据的集合.应用程序如果想长期保存数据,就必须将数据存储到文件中,这就涉及到文件的操作.而在编写网站应用程序的过程中,有许多地方要对文件 ...

  7. 如何限制上传服务器的文件容量,如何通过配置php文件限制上传文件的大小

    在网站开发的过程中,为了确保能够充分利用服务器的空间,在开发上传功能时,必须对上传文件的大小进行控制.那么我们如何进行对上传文件的大小进行控制呢? 控制文件的大小可以从两个方面入手: 第一个是在PHP ...

  8. html5 上传超大文件,HTML5教程 如何拖拽上传大文件

    本篇教程探讨了HTML5教程 如何拖拽上传大文件,希望阅读本篇文章以后大家有所收获,帮助大家HTML5+CSS3从入门到精通 . < 前言: 大文件传输一直是技术上的一大难点.文件过大时,一些性 ...

  9. Python实现向s3共享存储上传和下载文件

    Python实现向s3共享存储上传和下载文件 https://www.cnblogs.com/liang545621/p/10298617.html 使用Python从S3上传和下载文件 https: ...

最新文章

  1. 洛谷 P3368 【模板】树状数组 2
  2. Page Ability生命周期内容介绍!
  3. html div p 区别,html中div br p三者有什么区别?
  4. Disturbed People(思维)
  5. 如何在OS X中打开或关闭鼠标定位器
  6. BZOJ 4154 kd-tree dfs序 + 二维空间的区间(矩阵)更新单点查找
  7. auc 和loss_精确率、召回率、F1 值、ROC、AUC 各自的优缺点是什么?
  8. 契税申报期限_纳税申报的5个小常识,不知道的不是合格的财务人!
  9. 数字后端设计实现之时钟树综合实践篇
  10. U盘引导启动LINUX
  11. JAVA:实现求Median中位数算法(附完整源码)
  12. 独立元器件搭建的逻辑门电路和仿真(一)
  13. 关于自己学C的点滴记录
  14. 基础呀基础,用二极管防止反接,你学会了吗?
  15. Win7下配置php运行环境
  16. 职场最高级的聪明是靠谱,到底一个人怎样才算真正靠谱?
  17. 让微积分穿梭于工作与学习之间(23):用极限的思想把一元一次方程和一元二次方程的根式解统一起来
  18. Tomcat - 解决which must be escaped when used within the value错误
  19. 你每天走的步数,手机是怎么算出来的?
  20. 2004年9月13日

热门文章

  1. Perforce-Server迁移
  2. Web文件管理原码.rar
  3. [转载] python集合add和update_python 集合set remove update add
  4. 简单解决 WIN10更新后 远程桌面提示 CredSSP加密Oracle修正的问题
  5. Bzoj4480: [Jsoi2013]快乐的jyy 广义后缀自动机 倍增 哈希 manacher
  6. HTML5学习笔记(二十六):JavaScript的错误处理
  7. sampleFactory(女娲造人)
  8. ubuntu10.10和windows双系统启动顺序的修改(转)
  9. 【★原创★】夜晚,不要让电白白流失!
  10. PyTorch 入坑七:模块与nn.Module学习