Retrieve the file name while using file type input

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

I have a jsp with this code snippet in it.

Choose Fil
5条回答
  •  暖寄归人
    2021-02-19 20:33

    But, first of all, you will need Commons Fileupload API, which will help you to use file.getFieldName() to display the Form Field Name and file.getContentType() to display Type of File and file.getName() to display File Name

    public String convertFile(HttpServletRequest request, HttpSession session) {
      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(!isMultipart) {
                out.println("File Not Uploaded");
        }
        else{
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);
              } catch (FileUploadException e) {
                e.printStackTrace();
            }
            try {
                FileItem file = (FileItem) items.get(0);
                out.print("Field Name :"+file.getFieldName()); // Display the field name
                out.print("Content Type :"+file.getContentType()); // Display Type of File
                out.print("File Name :"+file.getName()); // Display File Name
            } catch (Exception e) {
                out.print(e);
            }
        }
     }
    

提交回复
热议问题