如何上传图片文件?
使用SpringMVC
只需要配置解析文件即可
<!-- 配置文件解析器对象,要求id名称必须是multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver>
<property name="maxUploadSize" value="10485760"/>
</bean>
java代码实现
使用了upload.getOriginalFilename()获取文件名字
使用了upload.transferTo()上传文件路径与名字
注意
- 页面input下的name必须与MultipartFile 变量名保持一致
- 如果生成的图片出现乱码,解析一下
new String(upload.getOriginalFilename().getBytes(“ISO-8859-1”),“UTF-8”)
@RequestMapping("/testFileUpload3")
public String testFileUpload3(HttpServletRequest request, MultipartFile upload) throws IOException {
// request.setCharacterEncoding("utf-8");
//1.定义路径
String path = request.getSession().getServletContext().getRealPath("/Users/mac/Desktop/file");
File file = new File(path);
if(!file.exists()){
//没有路径创建
file.mkdirs();
}
//直接获取就行
//乱码解决方案
String filename = new String(upload.getOriginalFilename().getBytes("ISO-8859-1"),"UTF-8");
System.out.println(filename);
String uuid = UUID.randomUUID().toString().replace("-", "");
filename=uuid+"_"+filename;
//发送到指定路径下
upload.transferTo(new File(path,filename));
return "success";
}