SpringMVC文件上传(文件名不重复)
1)表单项type=“file”
2)表单的提交方式是post
3)表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data”
单文件上传步骤
1)导入fileupload和io坐标
2)配置文件上传解析器
3)编写文件上传代码
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242800"/>
<!--上传单个文件的大小-->
<property name="maxUploadSizePerFile" value="5242800"/>
<!--上传文件的编码类型-->
<property name="defaultEncoding" value="UTF-8"/>
</bean>>
编写业务层 Controller 上传代码
@RequestMapping(value = "mmm")
@ResponseBody
public String say12(MultipartFile files) throws IOException {
String filen = files.getOriginalFilename();
File file = new File("H:\\"+filen);
int i = 0;
while (file.exists()){
i++;
file = new File("H:\\"+i+filen); //如果文件存在名称相同的则加前缀或者加时间戳
}
file.createNewFile();
InputStream ins = files.getInputStream();
BufferedInputStream bis =new BufferedInputStream(ins);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] by =new byte[1024];
int len;
while ((len = bis.read(by)) != -1){
bos.write(by);
}
bos.close();
bis.close();
return "Successupload!";
}
form表单
<form action="http://localhost:8080/user/mmm" method="post" enctype="multipart/form-data">
<input type="file" name="files">
<input type="submit" value="ssss">
</form>
上传结果
本文来自博客园,作者:冰莫莫,转载请注明原文链接:https://www.cnblogs.com/icemomo/p/16028515.html