目录
一、上传图片
二、下载(展示)图片
一、上传图片
(1)jsp中:
(2)java后端接收
@RequestMapping("add")
public void add(Integer type, MultipartFile fileName) throws Exception {
//type可直接获取到
System.out.println(type);
//文件保存 这里的fileName1是后台保存的图片名(UUID)
String fileName1 = FileUtils.upLoad(fileName, "D:/sddr/");
}
注:FIleUtils工具类中的upload方法:
public static String upLoad(MultipartFile fileName, String filePath) throws Exception {
if (null != fileName && !fileName.isEmpty()) {
// 存入的文件名要唯一
String fileNameUUID = UUID.randomUUID().toString().replace("-", "");
String fileSuffix = fileName.getOriginalFilename()
.substring(fileName.getOriginalFilename().lastIndexOf("."));
// 文件夹不存在时创建
String mir = filePath;
File file = new File(mir);
if (!file.exists()) {
file.mkdirs();
}
// 把页面的图片复制到服务器
fileName.transferTo(new File(mir + fileNameUUID + fileSuffix));
return fileNameUUID + fileSuffix;
}
return null;
}
二、下载(展示)图片
(1)jsp里:
上面这是展示,如果新建一个标签把type改为按钮,value写成上面src中的值,就是下载了。
(2)java后端
@RequestMapping("download")
public void download(String fileName, HttpServletResponse response) throws Exception {
FileUtils.downLoad(response, fileName, "D:/sddr/");
}
注:FIleUtils工具类中的download方法:
public static void downLoad(HttpServletResponse response, String fileName, String filePath) throws Exception {
if(!StringUtils.isEmpty(fileName) && !"null".equals(fileName)) {
FileInputStream in = new FileInputStream(new File(filePath + fileName));
OutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
}
}



