小编典典

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

jsp

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

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

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


阅读 240

收藏
2020-06-10

共1个答案

小编典典

这是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

这里是一个load()方法来调用doPost()或doGet()

    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>
2020-06-10