避免重复文件上传

时间:2016-09-20 09:17:26

标签: servlets upload duplicates

我想设计一个上传.xlsx文件但没有重复的应用程序。重复的条件如下:    如果用户尝试上载与先前在服务器上可用的数据和名称相同的文件,则不应上载该文件。    但如果他上传的文件与服务器上以前提供的数据和名称不同,那么该文件应该上传到服务器上。

我写的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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<script> 
var _validFileExtensions = [".xlsx"];    
function Validate(oForm) {
    var arrInputs = oForm.getElementsByTagName("input");
    for (var i = 0; i < arrInputs.length; i++) {
        var oInput = arrInputs[i];
        if (oInput.type == "file") {
            var sFileName = oInput.value;
            if (sFileName.length > 0) {
                var blnValid = false;
                for (var j = 0; j < _validFileExtensions.length; j++) {
                    var sCurExtension = _validFileExtensions[j];
                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                        blnValid = true;
                        break;
                    }
                }

                if (!blnValid) {
                    alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                    return false;
                }
            }
        }
    }

    return true;
}
</script>
<center>
<h3> File Upload</h3>
<br>
<form action="./UploadServlet" method="post" enctype="multipart/form-data" onsubmit="return Validate(this);">
Select .xlxs to upload <br>
<input type="file" name="uploadFile" size="50">
<br><br>
<input type="submit" value="Upload File">
</form>
</center>
</body>
</html>

我的servlet如下:

package com.ideas.webapp;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet(name = "servlet", urlPatterns = { "/UploadServlet" })

public class uploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String UPLOAD_DIRECTORY = "upload";



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(req)) {
            PrintWriter writer = resp.getWriter();
            writer.println("Request does not contain upload data");
            writer.flush();
            return;
        }

        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);


        // constructs the directory path to store upload file
        String uploadPath = getServletContext().getRealPath("")
            + File.separator + UPLOAD_DIRECTORY;
        // creates the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(req);
            Iterator iter = formItems.iterator();

            // iterates over form's fields
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    // saves the file on disk
                    item.write(storeFile);
                }
            }
           System.out.println("Upload has been done successfully!");
        } catch (Exception ex) {
            System.out.println("There was an error: " + ex.getMessage());
        }
        getServletContext().getRequestDispatcher("/uploadFile.jsp").forward(req, resp);
    }       
        }

1 个答案:

答案 0 :(得分:0)

嗯,最简单的方法是保留以前上传文件的校验和列表(MD5,SHA1,...选择一个),并检查当前上传文件的校验和是否在列表中。

要保存带宽,您还可以执行检查浏览器端(使用AJAX获取校验和列表),您还必须在服务器端执行此操作,因为总是用户可以避免浏览器端检查并直接上传文件。在这种情况下,您需要检测并拒绝它。