注意点:
1、使用注解@MultipartConfig将一个Servlet标识为支持文件上传。
2、Servlet3.0将multipart/form-data的POST请求封装成Part,通过Part对上传的文件进行操作。
3、WebUploader参照网上教程实现。
4、引入webuploader.css、webuploader.js、Uploader.swf
upload.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>测试</title> <script type="text/javascript" src="${pageContext.request.contextPath }/JS/jquery-1.8.3.min.js"></script> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/JS/WebUploader/webuploader.css"> <script type="text/javascript" src="${pageContext.request.contextPath }/JS/WebUploader/webuploader.js"></script> <script type="text/javascript"> var state = "pending"; var uploader; $().ready(function(){ init(); }); function init(){ if (!uploader) { uploader = WebUploader.create({ swf : "${pageContext.request.contextPath }/JS/WebUploader/Uploader.swf", server : "${pageContext.request.contextPath }/servlet/UploadServlet", auto : false, pick : "#selectFile", resize : false }); } uploader.on("fileQueued",function(file){ $("#fileInfo").append(‘<div id="‘+file.id+‘">‘+file.name+‘<p class="state">等待上传</p></div>‘); }); uploader.on("uploadProgress",function(file,percentage){ var fileId = $("#"+file.id), percent = fileId.find(".progress .progress-bar"); if(!percent.length){//避免重复创建 percent = $(‘<div class="progress progress-striped active"><div class="progress-bar" role="progressbar" style="width: 0%"></div></div>‘) .appendTo(fileId).find(‘.progress-bar‘); } fileId.find(‘p.state‘).text(‘上传中‘); percent.css( ‘width‘, percentage * 100 + ‘%‘ ); }); uploader.on( ‘uploadSuccess‘, function( file ) { $( ‘#‘+file.id ).find(‘p.state‘).text(‘已上传‘); }); uploader.on( ‘uploadError‘, function( file ) { $( ‘#‘+file.id ).find(‘p.state‘).text(‘上传出错‘); }); uploader.on( ‘uploadComplete‘, function( file ) { $( ‘#‘+file.id ).find(‘.progress‘).fadeOut(); }); uploader.on( ‘all‘, function( type ) { if ( type === ‘startUpload‘ ) { state = ‘uploading‘; } else if ( type === ‘stopUpload‘ ) { state = ‘paused‘; } else if ( type === ‘uploadFinished‘ ) { state = ‘done‘; } if ( state === ‘uploading‘ ) { $("#startUpload").text(‘暂停上传‘); } else { $("#startUpload").text(‘开始上传‘); } }); //开始上传 $("#startUpload").on( ‘click‘, function() { if ( state === ‘uploading‘ ) { uploader.stop(); } else { uploader.upload(); } }); //上传出错时触发 uploader.on( "uploadError", function( obj, reason ) { var errorMessage = response.message; alert(reason,3); }); } </script> </head> <body> <div id="uploader"> <div id="fileInfo"></div> <div class="btns"> <div id="selectFile">选择文件</div> <button id="startUpload">开始上传</button> </div> </div> </body> </html>
uploadConfig.properties
配置文件上传的根路径、文件大小限制、后缀限制:
fileSystemPath=F:/UploadFile #maxSize=123456789 #fileSuffix=jpg,doc,docx,xls
UploadServlet.java:
使用@WebServlet注解来访问servlet
package com.test.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Properties; import java.util.Random; 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("/servlet/UploadServlet") @MultipartConfig public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UploadServlet() { super(); } @Override public void destroy() { // TODO Auto-generated method stub super.destroy(); } @Override public void init() throws ServletException { // TODO Auto-generated method stub super.init(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); InputStream proIn = getClass().getClassLoader().getResourceAsStream("uploadConfig.properties"); Properties properties = new Properties(); properties.load(proIn); String fileSystemPath = properties.getProperty("fileSystemPath");//系统根路径 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); String filePath = "upload" + "/" + ymd; String savePath = fileSystemPath + "/" + filePath; //创建文件夹 File saveDir = new File(savePath); if(!saveDir.exists()){ saveDir.mkdirs(); } Collection<Part> parts = request.getParts(); for(Part part : parts){ String contentDisposition = part.getHeader("content-disposition"); String fileName = getFileName(contentDisposition); if(fileName.equals("")){ continue; }else{ String pureFileName = fileName.substring(0, fileName.lastIndexOf(".")); String suffix = fileName.substring(fileName.lastIndexOf(".")+1); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddhhmmss"); String saveFileName = pureFileName + "-" + sdf1.format(new Date()) + "-" + new Random().nextInt(1000) + "." + suffix; part.write(savePath + "/" + saveFileName); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public String getFileName(String contentDisposition){ String[] strArr1 = contentDisposition.split(";"); if(strArr1.length < 3){ return ""; }else{ String[] strArr2 = strArr1[2].split("="); String fileName = strArr2[1]; fileName = fileName.replaceAll("\"", "");//把双引号去除掉 return fileName; } } }
时间: 2024-11-08 07:45:53