更新时间:2022-01-14 10:07:14 来源:极悦 浏览1019次
1.在maven中导入依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
2.在spring-mvc配置文件中添加
<!-- 定义文件解释器 -->
<bean name="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置文件大小:单位字节-->
<property name="maxInMemorySize" value="1024" />
<property name="defaultEncoding" value="UTF-8" />
<property name="maxUploadSize" value="5000000"/>
</bean>
3.定义上传文件工具类
package com.nz.homework.utils;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;
public class UploadUtils {
public String upload(String path,MultipartFile multipartFile){
//返回文件的类型,在此处中并没有用到,只是列出getContentType是返回文件的类型
String type = multipartFile.getContentType();
//拿到文件的原始名称,即例如a.jpg
String originalFilename = multipartFile.getOriginalFilename();
//判断是否为空
if (originalFilename==null){
return null;
}
//因为上传文件只有一个upload目录,所有的文件都会放在这个文件下,会堆积大量的文件,所以把文件进行分开在upload不同的目录中,利用hash算法就行计算分配目录。例如upload/4/5;或者upload/5/5;这种
//拿到文件原名称的hashcode
int hashCode = originalFilename.hashCode();
//拿到upload下第一个目录的名称upload/n
int dir1 = hashCode & 0xf;
//拿到upload下的n目录下的目录名称upload/n/n
int dir2 = (hashCode & 0xf0) >> 4;
//拼接路径,path是传过来的文件保存路径,即upload的真实路径,
String dir = path + File.separator+dir1 + File.separator + dir2;
把路径丢到File文件中
File file = new File(dir);
//如果d:\1\2这个文件夹不存在,才创建
if (!file.exists()){
file.mkdirs();
}
//生成新的UUID.randomUUID().toString():为了防止文件名重复
String newFileName = UUID.randomUUID().toString().replace("-","")+"."+originalFilename.substring(originalFilename.lastIndexOf(".")+1);
InputStream is = null;
OutputStream os = null;
try {
is = multipartFile.getInputStream();
os = new FileOutputStream(dir+File.separator+newFileName);
//对文件进行复制
FileCopyUtils.copy(is,os);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//返回文件的路径,以便保存到数据库中
return dir1+File.separator+dir2+File.separator+newFileName;
}
}
4.在service的实现类中实现
@Service("/bookService")
public class BookServiceImpl implements BookService {
private static final String UPLOAD_DIR= "D:\\code\\week15\\practice\\src\\main\\webapp\\upload";
//不建议用new UploadUtils,因为要低耦合,建议把UploadUtils类的upload方法换成静态的方法
private UploadUtils uploadUtils = new UploadUtils();
@Resource
BookMapper bookMapper;
@Override
public int insertBook(MultipartFile multipartFile, Book book) {
String newPath = uploadUtils.upload(UPLOAD_DIR, multipartFile);
//设置存到数据库的img路径
book.setImg(newPath);
return bookMapper.addBook(book);
}
}
5.controller层代码
@RequestMapping("/addBook")
//Result为工具类,参考上一篇的分页中有完整的Result代码
public Result addBook(MultipartFile multipartFile, Book book){
try {
if (multipartFile.isEmpty()){
return Result.error();
}
int rows = bookService.insertBook(multipartFile,book);
return Result.success(rows);
} catch (Exception e) {
log.error(e.getMessage());
}
return Result.error();
}
6.entity层代码
@Data
public class Book {
/**
* 图书ID
*/
private Integer bid;
/**
* 图书名称
*/
private String name;
/**
* 作者
*/
private String author;
private Double price;
private Date crtTime;
private String Img;
}
1.第一步
2.第二步,点击External Souce
3.第三步,选择要上传的位置,web下的upload,点击upload,然后重启tomcat即可
<!DOCTYPE html>
<html lang="en" xmlns:border="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery.js"></script>
<script>
$(function () {
$("#upload").click(function () {
//$('#uploadForm')[0]为选择器,不规定为id选择器,前提是该选择器能获取file文件,然后放入到formData中
var formData = new FormData($('#uploadForm')[0]);
console.log(formData.get("file"))
if (formData ==={} || formData===""){
alert("请选择文件")
}
formData.append("multipartFile",formData.get("file"));
//调用formData的append方法,将book属性都添加进去,img填空白即可。
formData.append("name","龙哥传");
formData.append("author","龙哥");
formData.append("price","10.33");
formData.append("img","");
$.ajax({
type: 'post',
url: "http://localhost:8080/practice/book/addBook",
data: formData,
cache: false,
processData: false,
contentType: false,
success:(function (results) {
if (results.data!==0 || results.status === 200){
alert("成功")
}
}),
error:(function () {
alert("上传失败");
}),
});
});
});
</script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
文件:<input id="file" type="file" name="file"/>
</form>
<button id="upload">上传文件</button>
</body>
</html>
0基础 0学费 15天面授
Java就业班有基础 直达就业
业余时间 高薪转行
Java在职加薪班工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习