servlet show upload progress upload files +

Renderings

b.gif

Functional Description

1. jquery.form.js asynchronous uploads and displays upload progress
2.servlet save files uploaded to the specified folder
file has been uploaded 3. Review
4. different file types are displayed with different icons

download

https://github.com/houxinlin/ServletUploadFile

Project structure

image.png

Implementation process

1.Servlet Code
MainServlet.java

MainServlet responsible for the main interface information, traversal has uploaded a file name passed to the 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 responsible for saving the file, if the file has the same name, correct

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);
    }

}

Auxiliary class
FilesUtils.java and 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("失败")
        }
    })

}

Guess you like

Origin www.cnblogs.com/HouXinLin/p/11069501.html