SSM项目:前端上传图片后台保存图片,并在前端显示
1.前端部分
<input type="file" accept="imaget/jpeg" id="myfile" onchange="showp" />
<div id="imgs"></div><!--图片显示的位置-->
mounted() {
var inp = document.querySelector("#myfile");
inp.onchange = function() {
//console.log(this.files);
for (var i = 0; i < this.files.length; i++) {
var file = this.files[i];
//console.log(file);
var fr = new FileReader();
fr.readAsDataURL(file);
fr.onload = function() {
//console.log(this.result);
var img = new Image();
img.src = this.result;
document.getElementById("imgs").appendChild(img);
//发送图片到容器
this.imasrc = img.src
if (this.imasrc != '') {
document.getElementById("myfile").style.display = "none",
document.getElementById("txbq").style.display = "none"
}
}
}
}
},
submit(e) {
//提交方法,将图片发送到后端保存
var imgurl = document.querySelector('input[type=file]').files[0];
let dataform = new FormData();
dataform.append("pic", imgurl);
this.$refs.form.validate().then((result) => {
request({
url:'/register', data:dataform,
headers: {
'Content-Type': 'multipart/form-data'
},
method:'post'
}).then(res => {
})
}
2.controller部分
@RestController("registerController")
public class RegisterController {
@PostMapping("register")
public String uploadFile(@RequestParam("pic") MultipartFile pic) throws IOException, ServletException {
String fileName = pic.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf('.'));
String newFileName = new Date().getTime() + suffix;
try {
File file2 = new File("D:\\image");
if (!file2.exists()) {
//目录不在创造目录
file2.mkdirs();
}
File newFile2 = new File("D:\\image\\" + newFileName);
pic.transferTo(newFile2);
return "1";
} catch (Exception e) {
e.printStackTrace();
return "失败";
}
}
}
3.tomcat配置文件部分
在tomcat配置文件中添加以下配置(conf/server.xml文件)
<Context path="/upload" docBase="D:/image" reloadable="true"></Context>
4.idea配置
勾选图片上的选项,不然配置的配置文件不生效。
5.前端显示后端保存的图片
<img :src="user.img">
user: {
img: 'http://localhost:8080/upload/' + this.$store.state.userinfo.pic
}
注意事项
1.最好不要将文件存在tomcat文件下,而是将文件存在本地磁盘。因为tomcat下的文件很容易就会被清掉。
2.配置文件修改后,一定要修改idea的tomcat配置,不然配置文件不生效。
3.前端显示的地址是:http://localhost:8080/upload/+图片名称,注意不要加入项目地址,这样会导致找不到图片,我因为加了项目地址,这个错误找了好久。