一搭建好springmvc框架;
二上传图片代码编写
1.导入上传图片的相关jar包;
2.配置springmvc.xml
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="200000" />
</bean>
3.代码如下
@RequestMapping("/upload")
public String uploade(String fileName, MultipartFile file1, HttpServletRequest request) throws IOException {
String path = request.getServletContext().getRealPath("/upload");
File file = new File(path);
InputStream in = file1.getInputStream();
if (!file.exists()) {// 存储路径不存在,则新建
file.mkdirs();
}
// 复制文件
BufferedInputStream bufInputStream = new BufferedInputStream(in);
// String contentType = file1.getContentType();
String file1name = file1.getOriginalFilename();
String fileFix = file1name.substring(file1name.lastIndexOf("."));
String newFileName = fileName + fileFix;
File newFile = new File(path + "/" + newFileName);
OutputStream outputStream = new FileOutputStream(newFile);
BufferedOutputStream bufOutputStream = new BufferedOutputStream(outputStream);
byte[] items = new byte[1024 * 1024];
int i = 0;
while ((i = bufInputStream.read(items)) != -1) {
bufOutputStream.write(items, 0, i);
bufOutputStream.flush();// 刷新流
}
bufOutputStream.close();
outputStream.close();
bufInputStream.close();
in.close();
return "list";
}
二批量上传文件
@RequestMapping("/uploadMany")
public String uploadMany(@RequestParam("file1")MultipartFile[] file1, HttpServletRequest request) throws IOException {
//创建上传位置文件夹
String path = request.getServletContext().getRealPath("/upload");
File file = new File(path);
if (!file.exists()) {// 存储路径不存在,则新建
file.mkdirs();
}
//获取文件流
for(MultipartFile fi : file1){
InputStream in = fi.getInputStream();
// 复制文件
BufferedInputStream bufInputStream = new BufferedInputStream(in);
// String contentType = fi.getContentType();
String file1name = fi.getOriginalFilename();
String fileFix = file1name.substring(file1name.lastIndexOf("."));
String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + fileFix;
System.out.println(newFileName);
File newFile = new File(path + "/" + newFileName);
OutputStream outputStream = new FileOutputStream(newFile);
BufferedOutputStream bufOutputStream = new BufferedOutputStream(outputStream);
byte[] items = new byte[1024 * 1024];
int i = 0;
while ((i = bufInputStream.read(items)) != -1) {
bufOutputStream.write(items, 0, i);
bufOutputStream.flush();// 刷新流
}
bufOutputStream.close();
outputStream.close();
bufInputStream.close();
in.close();
}
return "list";
}