使用文件类型输入时检索文件名 [英] Retrieve the file name while using file type input

查看:59
本文介绍了使用文件类型输入时检索文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有此代码段的 jsp .

I have a jsp with this code snippet in it.

<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");
}

我无法检索文件名,它显示 null .我知道我可以使用JQuery或javascript检索名称,但是我不想同时使用它们.我想用纯Java做到这一点.谁能帮我吗?

I am unable to retrieve the name of the file, it shows null. I know that I can retrieve the name using JQuery or javascript, but I don't want to use them both. I want to do it using pure java. Can anyone please help me?

推荐答案

上载文件时, request

When you upload the file, request is instance of org.springframework.web.multipart.MultipartHttpServletRequest. So you can cast it in your method convertFile(). See below :

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页面中选择的文件的名称.

However I am unable to retrieve (receiving null value) the name of the file that I chose in the JSP page.

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

---> To get file name you can get it as :

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:

To make file upload work, you need to make sure you are creating multipart resolver bean as below :

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

参考资料: Spring文档

这篇关于使用文件类型输入时检索文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆