网站首页 > 技术文章 正文
前言:
??我们在设计自己的网站的时候,一定会遇到上传图片的功能,比如:用户头像,商品图片。
??这篇文章将带着大家设计一个可以使用的图片上传功能,请大家一步一步来,让我们在码路上越走越远。
前端:
组件引入
前端我们使用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);
}
拿到这些参数后可以根据某些参数去定位数据库中的某条记录,然后将图片位置保存入数据库中,以便后续访问。
- 上一篇: WebUploader实现图片上传功能
- 下一篇: LayUI+asp.net图片上传详解
猜你喜欢
- 2024-11-25 超强 Vue+Electron 图床上传工具PicGo
- 2024-11-25 JAVA全栈CMS系统vue图片/视频上传组件,多图上传及删除功能11
- 2024-11-25 SpringCloud+vue实现图片裁剪缩放上传
- 2024-11-25 Node.js实现将文字与图片合成技巧
- 2024-11-25 Nodejs之MEAN栈开发(四)-- form验证及图片上传
- 2024-11-25 基于业务场景下的图片/文件上传方案总结
- 2024-11-25 几行代码实现上传接口,白嫖Github做为在线图床
- 2024-11-25 我带的实习生竟然把图片直接存到了服务器上!崩溃了
- 2024-11-25 Fabric.js 将本地图像上传到画布背景
- 2024-11-25 前端JS判断上传文件是否是图片
你 发表评论:
欢迎- 599℃几个Oracle空值处理函数 oracle处理null值的函数
- 591℃Oracle分析函数之Lag和Lead()使用
- 579℃0497-如何将Kerberos的CDH6.1从Oracle JDK 1.8迁移至OpenJDK 1.8
- 575℃Oracle数据库的单、多行函数 oracle执行多个sql语句
- 571℃Oracle 12c PDB迁移(一) oracle迁移到oceanbase
- 564℃【数据统计分析】详解Oracle分组函数之CUBE
- 550℃最佳实践 | 提效 47 倍,制造业生产 Oracle 迁移替换
- 545℃Oracle有哪些常见的函数? oracle中常用的函数
- 最近发表
- 标签列表
-
- 前端设计模式 (75)
- 前端性能优化 (51)
- 前端模板 (66)
- 前端跨域 (52)
- 前端缓存 (63)
- 前端aes加密 (58)
- 前端脚手架 (56)
- 前端md5加密 (54)
- 前端路由 (61)
- 前端数组 (73)
- 前端js面试题 (50)
- 前端定时器 (59)
- 前端懒加载 (49)
- 前端获取当前时间 (50)
- 前端接口 (50)
- Oracle RAC (76)
- oracle恢复 (77)
- oracle 删除表 (52)
- oracle 用户名 (80)
- oracle 工具 (55)
- oracle 内存 (55)
- oracle 导出表 (62)
- oracle 中文 (51)
- oracle的函数 (57)
- 前端调试 (52)
本文暂时没有评论,来添加一个吧(●'◡'●)