使用文件类型输入时检索文件名

2022-09-04 07:37:37

我有一个带有此代码片段的内容。jsp

<form name="AudioFileConversionForm" enctype="multipart/form-data" method="post" >
Choose File: <input type="file" id="audioFile" name="audioFile"><br>
<input type="submit" value="upload">
</form>

这是我在 中的控制器。spring

public String convertFile(HttpServletRequest request, HttpSession session) {

    String audioFile = request.getParameter("audioFile");
    System.out.println(request.getParameter("audioFile"));
    System.out.println("Audio File Conversion Successful");
}

我无法检索文件的名称,它显示.我知道我可以使用JQuery或javascript检索名称,但我不想同时使用它们。我想用纯java来做。任何人都可以帮我吗?null


答案 1

当您上传文件时,是 org.springframework.web.multipart.Multipart.MultipartHttpServletRequest 的实例。因此,您可以在方法中将其投射。见下文:requestconvertFile()

public String convertFile(HttpServletRequest request, HttpSession session) {
    // cast request
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    // You can get your file from request
    CommonsMultipartFile multipartFile =  null; // multipart file class depends on which class you use assuming you are using org.springframework.web.multipart.commons.CommonsMultipartFile

    Iterator<String> iterator = multipartRequest.getFileNames();

    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        // create multipartFile array if you upload multiple files
        multipartFile = (CommonsMultipartFile) multipartRequest.getFile(key);
    }

    // logic for conversion
}

但是,我无法检索(接收空值)我在 JSP 页中选择的文件的名称。

---> 要获取文件名,您可以将其获取为:

multipartFile.getOriginalFilename();  // get filename on client's machine
multipartFile.getContentType();       // get content type, you can recognize which kind of file is, pdf or image or doc etc
multipartFile.getSize()          // get file size in bytes

要使文件上传正常工作,您需要确保正在创建多部分解析器Bean,如下所示:

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>
</bean>

参考 : 弹簧文档


答案 2

使用多部分文件实用程序并尝试此操作

MultipartRequest multipartRequest = (MultipartRequest) request;
                Map map = multipartRequest.getFileMap();
                MultipartFile mfile = null;
                for (Iterator iter = map.values().iterator(); iter.hasNext();) {
                    mfile = (MultipartFile) iter.next();
                                String fileName = mfile.getOriginalFilename()
    }

或者你可以尝试apache commons文件上传。

查看此链接 : http://commons.apache.org/fileupload/using.html


推荐