前言:
我们在设计自己的网站的时候,一定会遇到上传图片的功能,比如:用户头像,商品图片。
这篇文章将带着大家设计一个可以使用的图片上传功能,请大家一步一步来,让我们在码路上越走越远。
前端:
组件引入
前端我们使用element-ui的组件。我这里以html加js的方式
1:引入vue.js,axios.js,element-ui。
基础文件上传
2:element-ui中有多个例子,我们使用其中一个:
class=”avatar-uploader” action=”/Manage/upBusinessImage” :show-file-list=”false” :on-success=”handleAvatarSuccess” :before-upload=”beforeAvatarUpload”> .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 = 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包: commons-io commons-io 2.11.0 基础文件上传 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); } 拿到这些参数后可以根据某些参数去定位数据库中的某条记录,然后将图片位置保存入数据库中,以便后续访问。 阅读前请先查看【免责声明】本文内容由互联网用户自发贡献,该文观点仅代表作者本人,本站仅供展示。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 1217266901@qq.com 举报,一经查实,本站将立刻删除。 转载请注明出处:https://jingfakeji.com/tech/26756.html