当您上传文件时,request
是org.springframework.web.multipart.MultipartHttpServletRequest
. 因此,您可以将其转换为您的方法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>
参考:Spring 文档