Retrieve the file name while using file type input

前端 未结 5 1616
南旧
南旧 2021-02-19 19:58

I have a jsp with this code snippet in it.

Choose Fil
5条回答
  •  心在旅途
    2021-02-19 20:29

    File name cannot be directly retrieved. You can use Apache Commons Fileupload API -

    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    
    // Parse the request
    List /* FileItem */ items = upload.parseRequest(request);
    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
    
        if (item.isFormField()) {
           // Process a normal field
           String name = item.getFieldName();
           String value = item.getString();
    
        } else {
            // Process a file upload field 
        String fileName = item.getName();
        // DO further processing
    
        }
    }
    

    More details -

    http://commons.apache.org/fileupload/using.html

    It can also be done with just Java but obviously more code will be required.

提交回复
热议问题