步骤一:导入文件上传工具类(上传路径需要修改)
package com.nine.util;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
public class FileUtil {//图片上传工具类
public static String uploadFile(MultipartFile file, HttpServletRequest request) throws Exception{
String pathRoot = request.getSession().getServletContext().getRealPath("");
System.out.println(pathRoot);
//生成uuid作为文件名称
String uuid= UUID.randomUUID().toString().replaceAll("-","");
//获得文件类型(可以判断如果不是图片,禁止上传)
String contextType=file.getContentType();
//获取文件后缀名称
String fileName=uuid+"."+contextType.substring(contextType.indexOf("/")+1);
String path="/resources/img/"+fileName;
copyInputStreamToFile(file.getInputStream(),new File("D:\\MyProject\\nine_news\\web\\"+path));//记得改成自己项目所在路径
file.transferTo(new File(pathRoot+path));
System.out.println(pathRoot+path);
//返回文件保存到数据库的路径
return path;
}
public static void copyInputStreamToFile(InputStream inputStream, File file) throws Exception{
if (!file.exists()) {
file.createNewFile();
}
OutputStream outputStream=new FileOutputStream(file);
byte[] arr=new byte[1024];
int len=0;
while ((len=inputStream.read(arr))!=-1){
outputStream.write(arr,0,len);
}
outputStream.close();
inputStream.close();
}
}
步骤二:Controller类 demo 注意参数MultipartFile 和注解
@RequestParam
//图书添加
@RequestMapping(value = "/addBook",method = RequestMethod.POST)
public String addBook(@RequestParam(value = "file",required = false) MultipartFile file, Book book) throws Exception{
//判断文件上传是否为空
if (!file.isEmpty()){
//把上传的路径转为字符串存入路径
String picture= FileUtils.uploadFile(file);
//把路径存入
book.setPicture(picture);
}else {
book.setPicture("");
}
iBookService.addBook(book);
//重定向到查询的方法
return "redirect:/book/fuzzyBook";
}
步骤三:添加页面的demo
enctype="multipart/form-data"
<h2>图书添加</h2>
<form action="/book/addBook" enctype="multipart/form-data" method="post">
图书封面:<input type="file" name="file"/><br/>
图书名:<input type="text" name="name"/><br/>
图书评价:<input type="text" name="content"/><br/>
<input type="submit" value="添加"/>
</form>
步骤四:页面展示 图片 用thymeleaf模板的th标签
<td><img th:src="${book.picture}"/> </td>
步骤五:
POM配置文件
;<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>