当您上传文件时,是 org.springframework.web.multipart.Multipart.MultipartHttpServletRequest 的
实例。因此,您可以在方法中将其投射。见下文:request
convertFile()
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>
参考 : 弹簧文档