如何在JSP / Java中检索上传文件的完整路径

时间:2015-08-06 13:37:22

标签: java jsp path

如何从以下HTML代码中检索文件的完整路径:

<input type="file" name="upl">

请不要提供任何脚本方法,因为现代浏览器不允许这样做!

1 个答案:

答案 0 :(得分:0)

这是csv或xsl上传的例子

// location to store file uploaded
private static final String UPLOAD_DIRECTORY = "ressources/csv";

//name of the uploaded file
private static final String FILE_NAME="myFileName";

// upload settings
private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 30;  // 30MiB
private static final int MAX_FILE_SIZE      = 1024 * 1024 * 400; // 400MiB
private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 500; // 500MiB 

这里是一个在doPost()或doGet()

中调用的load()方法
    protected void load(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    RequestDispatcher dispatcher;   
    dispatcher= getServletContext().getRequestDispatcher("/Connection");

    // checks if the request actually contains upload file
            if (ServletFileUpload.isMultipartContent(request)) {

                // configures upload settings
                DiskFileItemFactory factory = new DiskFileItemFactory();
                // sets memory threshold - beyond which files are stored in disk
                factory.setSizeThreshold(MEMORY_THRESHOLD);
                // sets temporary location to store files
                factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

                ServletFileUpload upload = new ServletFileUpload(factory);

                // sets maximum size of upload file
                upload.setFileSizeMax(MAX_FILE_SIZE);

                // sets maximum size of request (include file + form data)
                upload.setSizeMax(MAX_REQUEST_SIZE);

                // constructs the directory path to store upload file
                String uploadPath = getServletContext().getRealPath("")
                        + File.separator+UPLOAD_DIRECTORY;

                //Create dir if needed
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }

                try {
                    // parses the request's content to extract file data
                    @SuppressWarnings("unchecked")
                    List<FileItem> formItems = upload.parseRequest(request);

                    if (formItems != null && formItems.size() > 0) {
                        // iterates over form's fields
                        for (FileItem item : formItems) {
                            // processes only fields that are not form fields
                            if (!item.isFormField() && item!=null) {
                                String fileName = new File(item.getName()).getName();
                                String fileNameToSave=FILE_NAME;

                                String filePath = uploadPath + File.separator + fileName;
                                String filePathToSave = uploadPath + File.separator + fileNameToSave;
                                FileNameExtensionFilter filterCSV=new FileNameExtensionFilter(null,"csv");
                                FileNameExtensionFilter filterXLS=new FileNameExtensionFilter(null,"xls");
                                File file= new File(filePath);

                                //Check file extension
                                if(filterCSV.accept(file)){

                                    File storeFile = new File(filePathToSave+".csv");                       
                                    //Save file on disk
                                    item.write(storeFile);
                                    Outils.importCSV(request);
                                }
                                if(filterXLS.accept(file)){

                                    File storeFile = new File(filePathToSave+".xls");                       
                                    //Save file on disk
                                    item.write(storeFile);
                                    Outils.importXLS(request);
                                }

                            }
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

在JSP中:

<form id="upload" enctype="multipart/form-data" 
          method="POST" action="YOUR ACTION">
    <input type="file" name="uploadFile"> 
    <input type="submit" value="Upload">
</form>
相关问题