网站首页 > 编程文章 正文
前言:
??我们在设计自己的网站的时候,一定会遇到上传图片的功能,比如:用户头像,商品图片。
??这篇文章将带着大家设计一个可以使用的图片上传功能,请大家一步一步来,让我们在码路上越走越远。
前端:
组件引入
前端我们使用element-ui的组件。我这里以html加js的方式
1:引入vue.js,axios.js,element-ui。
<script src="../static/js/util/vue.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
基础文件上传
2:element-ui中有多个例子,我们使用其中一个:
<el-upload
class="avatar-uploader"
action="/Manage/upBusinessImage"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<style>
.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;
}
</style>
<script>
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;
}
}
}
</script>
上面是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 = new FormData();
formData.append('file', file);
formData.append('clothesId',clothesId);
formData.append('styleId',styleId);
formData.append('imgUrl',imgUrl);
let data = await axios.post("/Manage/upBusinessImage",formData)
},
??说明一下如果要传递的是多个参数,则必须把多个参数整理成formData的形式进行发送。而到后端则需要用@RequestParam注解标识进行接收。
后端:
需要引入的jar包:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
基础文件上传
Controller层:
@RequestMapping(value = "/Manage/upBusinessImage",method = RequestMethod.POST)
public CommonResultVo uploadBusinessImage(@RequestParam(value = "file", required = false) MultipartFile file) {
return fileService.uploadImage(file,"D:/img/HeadImages/");
}
??因为只传递了文件,所以只需要一个MultipartFile类型的file接收就可以了。
server层:
//上传操作
private CommonResultVo uploadImage(MultipartFile file,String folder){
if (file == null) {
return CommonResultVoUtil.error("请选择要上传的图片");
}
if (file.getSize() > 1024 * 1024 * 10) {
return CommonResultVoUtil.error("文件大小不能大于10M");
}
//获取文件后缀
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
return CommonResultVoUtil.error("请选择jpg,jpeg,gif,png格式的图片");
}
String savePath = folder;
File savePathFile = new File(savePath);
if (!savePathFile.exists()) {
//若不存在该目录,则创建目录
savePathFile.mkdir();
}
//通过UUID生成唯一文件名
String filename = UUID.randomUUID().toString().replaceAll("-","") + "." + suffix;
try {
//将文件保存指定目录
//file.transferTo(new File(savePath + filename));
//File file1 = new File(file.getOriginalFilename());
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(savePath + filename));
} catch (Exception e) {
e.printStackTrace();
return CommonResultVoUtil.error("保存文件异常");
}
//返回文件名称
return CommonResultVoUtil.successWithData(filename,1);
}
??代码里的CommonResultVoUtil是我自定义的结果工具类,大家可以根据自己的需求自己构建,也可直接返回字符串成功或者失败。
自定义的多参数接口
与上面的区别只是多使用了几个参数:
@RequestMapping(value = "/Manage/upBusinessImage",method = RequestMethod.POST)
public CommonResultVo uploadBusinessImage(@RequestParam(value = "file", required = false) MultipartFile file,
@RequestParam(value = "clothesId", required = false) String clothesId,
@RequestParam(value = "styleId", required = false) String styleId,
@RequestParam(value = "imgUrl", required = false) String imgUrl) {
return fileService.uploadBusinessImage(file,clothesId,styleId,imgUrl);
}
拿到这些参数后可以根据某些参数去定位数据库中的某条记录,然后将图片位置保存入数据库中,以便后续访问。
猜你喜欢
- 2024-09-11 第39章 Django调用验证码(调用验证码接口)
- 2024-09-11 第6章 Vue组件高级(vue组件用法)
- 2024-09-11 【JavaScript】ES6之Promise用法详解及其应用
- 2024-09-11 前后端分离 Vue + Springboot 实现用户列表单页面开发(建议收藏)
- 2024-09-11 在 JS 中如何使用 Ajax 来进行请求
- 2024-09-11 express框架开发开始篇 方便以后写项目时候可拿过来直接使用
- 2024-09-11 Spring Cloud Alibaba 之 Gateway 服务网关跨域问题
- 2024-09-11 SpringBoot+Vue+Flowable,模拟一个请假审批流程
- 2024-09-11 Vue基础(2)(vue基础笔试题)
- 2024-09-11 vue.js快速入门(vue.js入门教程)
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- spire.doc (59)
- system.data.oracleclient (61)
- 按键小精灵源码提取 (66)
- pyqt5designer教程 (65)
- 联想刷bios工具 (66)
- c#源码 (64)
- graphics.h头文件 (62)
- mysqldump下载 (66)
- sqljdbc4.jar下载 (56)
- libmp3lame (60)
- maven3.3.9 (63)
- 二调符号库 (57)
- 苹果ios字体下载 (56)
- git.exe下载 (68)
- diskgenius_winpe (72)
- pythoncrc16 (57)
- solidworks宏文件下载 (59)
- qt帮助文档中文版 (73)
- satacontroller (66)
- hgcad (64)
- bootimg.exe (69)
- android-gif-drawable (62)
- axure9元件库免费下载 (57)
- libmysqlclient.so.18 (58)
- springbootdemo (64)
本文暂时没有评论,来添加一个吧(●'◡'●)