java上传图片到服务器 javaweb上传图片到指定路径

前言:
??我们在设计自己的网站的时候,一定会遇到上传图片的功能,比如:用户头像,商品图片 。
??这篇文章将带着大家设计一个可以使用的图片上传功能,请大家一步一步来,让我们在码路上越走越远 。
前端:
组件引入
前端我们使用element-ui的组件 。我这里以html加js的方式
1:引入vue.js,axios.js,element-ui 。
</script>
<link rel=”stylesheet” href=https://www.fajihao.com/i/”https://unpkg.com/element-ui/lib/theme-chalk/index.css”>
</script>
基础文件上传
2:element-ui中有多个例子,我们使用其中一个:
<el-upload
class=”avatar-uploader”
action=”/Manage/upBusinessImage”
:show-file-list=”false”
:on-success=”handleAvatarSuccess”
:before-upload=”beforeAvatarUpload”>
java上传图片到服务器 javaweb上传图片到指定路径

.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
export default {
data() {
return {
imageUrl: ”
};
},
methods: {
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isJPG = file.type === ‘image/jpeg’;
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error(‘上传头像图片只能是 JPG 格式!’);
}
if (!isLt2M) {
this.$message.error(‘上传头像图片大小不能超过 2MB!’);
}
return isJPG && isLt2M;
}
}
}
上面是element-ui中的一个例子 。我将会对其中的各个参数进行讲解 。
其中的样式,我们不进行讲解,直接复制就可以 。
el-upload中的参数:
action:后面是接口url,图片文件将会发送到该接口中 。
:show-file-list:是否显示上传的图片列表
:on-success:上传成功后要执行的操作,“:”代表与js代码进行了绑定 。
:before-upload:上传之前要执行的操作,比如检验是否是图片文件,图片的大小是否符合要求等 。
??在它的一个函数中使用了URL.createObjectURL(file.raw);方法,这个地方要注意:elementUI中 , 自带的方法中的file , 并不是指图片本身,而是他的一个dom 。如果要是拿他的图片 , 就要用file.raw 。
自定义上传方法
??通过上面的方式就可以将图片文件发送给后端 , 但是,这个只是基础的功能,往往我们的业务不会如此简单,比如:我们可能将商品id,等信息一同发送后端,以保证后端确定图片的作用 。此时上面的方式就满足不了我们的需求了 。
??为此我们需要设计自己的上传方法 。于是改造过程:
1:action后面的路径改为空:action=””
2:添加属性:http-request,后面跟自定义的方法名,例如::http-request=“uploader”
3:在js中书写自定义方法“uploader”
async uploader(params){
let file = params.file;
let clothesId;
let styleId;
let imgUrl;
clothesId = this.goodsModify.goodsId;
styleId = this.goodsModify.styleId;
imgUrl = this.goodsModify.goodsImg
formData = https://www.fajihao.com/i/new FormData();
formData.append(‘file’, file);
formData.append(‘clothesId’,clothesId);
formData.append(‘styleId’,styleId);
formData.append(‘imgUrl’,imgUrl);
let data = https://www.fajihao.com/i/await axios.post(“/Manage/upBusinessImage”,formData)
【java上传图片到服务器 javaweb上传图片到指定路径】},
??说明一下如果要传递的是多个参数,则必须把多个参数整理成formData的形式进行发送 。而到后端则需要用@RequestParam注解标识进行接收 。
后端:
需要引入的jar包:
commons-io
commons-io
2.11.0
基础文件上传
Controller层:
@RequestMapping(value = https://www.fajihao.com/i/“/Manage/upBusinessImage”,method = RequestMethod.POST)
public CommonResultVo uploadBusinessImage(@RequestParam(value = https://www.fajihao.com/i/“file”, required = false) MultipartFile file) {
return fileService.uploadImage(file,”D:/img/HeadImages/”);
}
??因为只传递了文件,所以只需要一个MultipartFile类型的file接收就可以了 。