[Java web] Servlet + bootstrap-fileinput achieve file upload function

This article documents how to use the bootstrap-fileinput plug and servlet achieve a cool file upload function.

Preview

Here Insert Picture Description

Introduction

What bootstrap-fileinput that?
bootstrap-fileinput is a very good HTML5 file upload plugin support bootstrap 3.x and 4.x versions, has a lot of features: multiple file selection. This plug-in can help you complete the most simple file upload function, and the use of bootstrap style. Also supports multiple file previews, images, text, html, video , audio, flash. It also supports ajax upload files, you can see the upload progress. Adding and deleting files support drag and drop.
how to download?
In its official website you can find the option to manually install, click the download package. Download the archive contains the core CSS and JS files, you can use the copy to your next project. Note that this plugin depends on JQuery, so the page should be first introduced JQuery.
Here Insert Picture Description
Other specific usage can refer to the official website, because the plug-in has a lot of extended features, such as switching form Ajax form submission or submission, a single file or multiple files to upload, which the callback was executed after a file is uploaded, and so on, the official website has been written very detail, here introduces the use of Servlet as a server how to accept the file upload plugin.

HTML code

Note: To use the bootstrap-fileinput plug-in, we need to first plug corresponding CSS file and JS file in the directory, so as to be referenced in HTML.

HTML code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Upload Image上传头像</title>

<!-- 加载Bootstrap的核心CSS文件 -->
<link href="./css/bootstrap.min.css" rel="stylesheet">
<link href="./css/fileinput.css" rel="stylesheet">

<!-- 加载cdn上的JQuery文件 -->
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<!--如果没有正常从网络上加载jquery的话,就加载本地jquery-->
<script>window.jQuery|| document.write('<script src="./js/vendor/jquery.min.js"><\/script>')</script>

<!-- 加载本地bootstrap核心js文件-->
<script src="./js/bootstrap.min.js"></script>

<!-- 加载本地bootstrap-fileinput核心js文件,注意文件加载顺序-->
<script src="./js/plugins/piexif.js"></script>
<script src="./js/plugins/sortable.js"></script>
<script src="./js/plugins/purify.js"></script>
<script src="./js/fileinput.js"></script>
<script src="./js/locales/zh.js"></script>

</head>
<body>
	<div class="container">
		<div class="row">
			<div class=" col-sm-12 col-lg-12 col-md-12 ">
				<div class="file-loading">
					<input id="input-705" name="kartik-input-705" type="file" accept="image/*" multiple>
				</div>
			</div>
		</div>
	</div>

	<script>
		//当网页加载完成后执行以下函数,实现对插件的初始化设置
		$(document).ready(function() {
				$("#input-705").fileinput({
					//设置允许上传文件的后缀
					allowedFileExtensions : ['jpg', 'png' ],
					//设置语言为中文
					language : "zh",
					//上传服务的URL,这个URL简写也可以,写完整的URL也可以
					//使用简写的话,在Ajax提交时会在前部加上当前所在的域(域=协议+ip+端口号),以组成完整的URL
					uploadUrl : "/你的项目名称/UploadImageServlet",
					//选择异步上传
					uploadAsync : true,
					//设置一次上传允许的最多文件数量
					minFileCount : 1,
					//设置一次上传允许的最少文件数量
					maxFileCount : 1,
					overwriteInitial : false,
					initialPreviewAsData : true,
					//设置enctype属性,默认为application/x-www-form-urlencode,但是这种属性不支持上传二进制文件,所以诞生了multipart/form-data
					enctype : "multipart/form-data",
				});
			});
	</script>
</body>
</html>

Servlet Code

An interesting point is that when you choose to upload multiple images, bootstrap-fileinput plug-in sends an Ajax request for each file, so we only need one file can be processed in time to write the Servlet.
Example, when we upload two images:
Here Insert Picture Description
Press F12 to open the Network, click the Upload button, you can see two requests sent to the Servlet:
Here Insert Picture Description
Specific code as follows:

package servlet;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.List;

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

/**
 * Servlet implementation class UploadImageServlet
 */
@WebServlet("/UploadImageServlet")
public class UploadImageServlet extends HttpServlet {
	  	private static final long serialVersionUID = 1L;
	     
	    // 上传文件存储目录
	    private static final String UPLOAD_DIRECTORY = "image";
	 
	    // 上传配置
	    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
	    
	    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			doPost(request, response);
		}
	    
	    /**
	     * 上传数据及保存文件
	     */
	    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
	        //如果没有匹配到对应sessionId的session,则返回null
	    	HttpSession session=request.getSession(false);
	        
	    	// 检测是否为multipart/form-data上传
	        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 = request.getServletContext().getRealPath("./") + UPLOAD_DIRECTORY;
	        
	        // 如果目录不存在则创建
	        File uploadDir = new File(uploadPath);
	        if (!uploadDir.exists()) {
	            uploadDir.mkdir();
	        }
	        
	        try {
	            // 解析请求的内容提取文件数据
	            @SuppressWarnings("unchecked")
	            List<FileItem> formItems = upload.parseRequest(request);
	            if (formItems != null && formItems.size() > 0) {
	                // 迭代表单数据
	                for (FileItem item : formItems) {
	                    // 使用item.isFormField()方法判断FileItem类对象封装的数据是否为普通文本表单字段,还是文件表单字段
	                    if (!item.isFormField()) {
	                        String fileName = item.getName();	
	                       
	                        String filePath = uploadPath + File.separator + fileName;
	                        File storeFile = new File(filePath);
	                        // 保存文件到硬盘
	                        item.write(storeFile);
	                    }
	                }
	            }
	        } catch (Exception ex) {
	        	ex.printStackTrace();
	            //上传失败
	        	response.setCharacterEncoding("utf-8");
	        	//返回Json字符串
		        String json = "{\"state\":\"0:failed\"}";
		        response.getWriter().write(json);
		        return ;
	        }
	        // 上传成功
	        response.setCharacterEncoding("utf-8");
	        //返回Json字符串
	        String json = "{\"state\":\"1:success\"}";
	        response.getWriter().write(json);
	        return ;
	    }
}
Published 61 original articles · won praise 16 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41427568/article/details/103619986