1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Springboot + vue 上传图片 显示图片

Springboot + vue 上传图片 显示图片

时间:2023-06-16 05:55:27

相关推荐

Springboot + vue 上传图片 显示图片

Springboot + vue 上传显示图片

上传图片:

前端:

<el-uploadclass="upload-facepic"action="#":on-preview="handlePreview":on-remove="handleRemove":before-remove="beforeRemove":multiple="false"ref="upload":http-request="uploadFile1":limit="1":auto-upload="true":on-change="edithandleChange":on-success="handleSuccess":on-exceed="handleExceed":file-list="fileList"><el-button size="small" type="primary">点击上传</el-button><div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png文件,且不超过500kb</div></el-upload>vue.js:handlePreview(){},handleRemove(file,fileList) {},beforeRemove() {},handleChange (file,fileList) {this.fileList.push(file)},handleSuccess() {},handleExceed () {},handleChange:function (file, fileList) {this.addForm.bookPic = file.name;},edithandleChange:function(file, fileList){this.editForm.bookPic = file.name;},uploadFile(param){let _self = this;let file = param.file;let formData = new FormData();//formData.append("card",JSON.stringify(this.addForm.card));formData.append("typeId",JSON.stringify(this.addForm.typeId));formData.append("file",file);let url = '/api/book/uploadFile';let config = {headers:{'Content-Type':'multipart/form-data'} //这里是重点,需要和后台沟通好请求头,Content-Type不一定是这个值};this.$axios.post(url,formData,config).then(res =>{if(res.data.code ==='0'){this.$message({message:'文件上传成功',type:'success'})}else{this.$message.error(res.data.msg);return false;}});},

后端:

@PostMapping(value = "/uploadFile")public CommonResponse uploadFile(@RequestParam Map<String,Object> map,@RequestParam("file") MultipartFile file) throws IOException {String typeId = map.get("typeId")==null?"":map.get("typeId").toString();// 文件名String fileName = file.getOriginalFilename();// 在file文件夹中创建名为fileName的文件assert fileName != null;int split = fileName.lastIndexOf(".");// 文件后缀,用于判断上传的文件是否是合法的String suffix = fileName.substring(split+1,fileName.length());//判断文件类型,因为我这边是图片,所以只设置三种合法格式String url = "";String path = PropertiesUtil.class.getClassLoader().getResource("upload/").getPath();if("jpg".equals(suffix) || "jpeg".equals(suffix) || "png".equals(suffix)) {// 正确的类型,保存文件try {path = path + "/" + typeId;File upload = new File(path);if(!upload.exists()) {upload.mkdirs();}File savedFile = new File(path +"/" +fileName);file.transferTo(savedFile);url = savedFile.getAbsolutePath();System.out.println("图片上传完毕,存储地址为:"+"/"+ typeId);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}else {//错误的类型,返回错误提示return new CommonResponse(ProjectConstants.SUCCESS_CODE,"文件上传失败,请重试!",null);}File savedFile;return new CommonResponse(ProjectConstants.SUCCESS_CODE,"文件上传成功",typeId +"/"+fileName);}

vue页面显示图片:

前端:

<img :src="src" />this.$axios.post('/api/book/showImg',{typeId:this.viewForm.typeId,fileName:this.viewForm.bookPic}, {responseType:'blob'}).then(response =>{console.log(response)let blob = new Blob([response.data]); // 返回的文件流数据let url = window.URL.createObjectURL(blob); // 将他转化为路径this.src = url})

后端接口:

/*** 获取图片地址*/@RequestMapping(value = "/showImg")@ResponseBodypublic void showImg(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String,Object> map) {String typeId = map.get("typeId")==null?"":map.get("typeId").toString();String fileName = map.get("fileName")==null?"":map.get("fileName").toString();String path = PropertiesUtil.class.getClassLoader().getResource("upload/").getPath();File imgFile = new File(path+"/"+typeId+"/"+fileName);FileInputStream fin = null;OutputStream output = null;response.setCharacterEncoding("utf-8");response.setContentType("application/octet-stream");response.setHeader("Content-Disposition","attachment;fileName="+fileName);response.setHeader("Content-type","application/octet-stream");try {output = response.getOutputStream();fin = new FileInputStream(imgFile);byte[] arr = new byte[1024 * 10];int n;while ((n = fin.read(arr)) != -1) {output.write(arr, 0, n);}output.flush();} catch (IOException e) {e.printStackTrace();}try {output.close();} catch (IOException e) {e.printStackTrace();}}

以上以文件流的形式显示图片。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。