servlet上传文件+上传进度显示

2019-08-08 00:00:00 上传 进度 上传文件

效果图

《servlet上传文件+上传进度显示》

功能描述

1.使用jquery.form.js实现异步上传功能,并显示上传进度
2.servlet中保存上传的文件到指定文件夹
3.查看已经上传的文件
4.不同文件类型用不同图标显示

下载

https://github.com/houxinlin/ServletUploadFile

项目结构

《servlet上传文件+上传进度显示》

实现过程

1.Servlet代码
MainServlet.java

MainServlet负责主界面信息,遍历已经上传的文件名,传递给jsp

@WebServlet("/MainServlet")
public class MainServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public MainServlet() {
        super();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + path + "/";
        
        System.out.println(basePath);
        List<String> list =FilesUtils.listDirFiles(Config.UPLOAD_PATH);
        Map<String, String> map =new HashMap<>();
        for (String string : list) {
            map.put(string, string.substring(string.lastIndexOf(".")+1, string.length()) +"");
            
        }
        request.setAttribute("files", map);
        request.setAttribute("basePath", basePath);
        request.getRequestDispatcher("upload/index.jsp").forward(request, response);
        
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

UploadServlet.java
UploadServlet负责保存文件,如果文件有同名的,则更正

package com.houxinlin.servlets;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Part part =request.getPart("file");
        if(part!=null) {
            saveFile(part.getInputStream(),Config.UPLOAD_PATH,part.getSubmittedFileName());
        }

    }
    private void saveFile(InputStream is,String rootPath , String name) {
        try {
            String tempName =name;
            
            Path path =Paths.get(rootPath, tempName);
            int index=0;
            //如果文件存在
            if(Files.exists(path)) {
            
                while(Files.exists(path)) {
                
                    name=(++index)+tempName;
                    path =Paths.get(rootPath, name);
                }
                System.out.println("文件存在,文件名改正为----"+name);
            }
            System.out.println("保存---->"+rootPath +File.separatorChar+name);
            Files.copy(is, Paths.get(rootPath, name));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

辅助类
FilesUtils.java和Configa.java

package com.houxinlin.servlets;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

public class FilesUtils {
    public  static List<String> listDirFiles(String rootPath){
        List<String> list =new ArrayList<>();
        
        Stream<Path> paths;
        try {
            paths = Files.list(Paths.get(rootPath));
            Iterator<Path> item =paths.iterator();
            while (item.hasNext()) {
                Path path =item.next();
                if(!Files.isDirectory(path)) {
                    list.add(path.getFileName()+"");
                }
            }
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }
}
package com.houxinlin.servlets;

public class Config {
    public static final String UPLOAD_PATH="D:\\upload";
}

js

$("#add-file").click(function(param) {
    param.stopPropagation();
    param.stopPropagation();
    $("#upload-layout").css("display", "block")
})

$("#select-file-btn").click(function(param) {
    document.getElementById("file-input").click();
})
$("#file-input").change(function() {
    $("#select-file-btn label").html($("#file-input").val());
    $("#up-btn #progress-value").css("width", 0 +"%");
    $("#up-btn .title").html("上传")

});

$("#up-btn").click(function(param) {
    $(this).css({
        "width" : "87%",
    });
    upload();

})

function upload(param) {

    $("#upload-form").ajaxSubmit({
        success : function(param) {
            $("#up-btn .title").html("完成")
        },
        uploadProgress : function(event, position, total, percentComplete) {
            var width =(position/total)*100;
            $("#up-btn #progress-value").css("width", width +"%");
            $("#up-btn .title").html(+"%")
            var value =parseInt(width);
            $("#up-btn .title").html(value+"%")
        },
        fail : function(param) {
            $("#up-btn .title").html("失败")
        }
    })

}

相关文章