目录
在返回给前端的URL上弄了好久,前端一直无法访问到URL,结果一直显示404。 倒腾了一上午发现是 文件路径映射的问题,后端部分有讲解决办法,可供大家参考
需求
前端的图片上传到服务器指定的文件目录,并且将URL返回给前端
前端部分(ElementUI+Vue.js)
ElementUI的导入和使用:(组件 | Element)
Vue.js的导入和使用:(Vue.js (vuejs.org))
<template> <div class=\"form-group\"> <el-upload action=\"http://localhost:8081/upload\" :on-preview=\"handlePreview\" accept=\'.jpg\' :limit=\"10\" > <el-button size=\"small\" type=\"primary\">点击上传</el-button> <div slot=\"tip\" class=\"el-upload__tip\">只能上传jpg/png文件,且不超过500kb</div> </el-upload> </div> </template> <script> export default { name: \"updateImg\", methods:{ handlePreview(file){ window.open(file.response.url); console.log(file.response.url); } } } </script> <style scoped> </style>
效果:
后端部分(SpringBoot)
1.先配置application.yml文件
file-save-path:要保存图片的位置 早上遇到404问题是因为 在 配置file-save-path时候 没有在最后的 images后加上 ‘\\’ 导致路径无法匹配到
server: port: 8081 file-save-path: D:\\SoftWare\\SpringToolSuite\\WorkPlace\\HelloWorld\\src\\main\\resources\\static\\images\\ spring: mvc: view: prefix: / suffix: .jsp
2.映射资源-重写WebMvcConfigurer接口,实现对资源的映射
package com.etc.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer{ @Value(\"${file-save-path}\") private String fileSavePath; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(\"/images/**\").addResourceLocations(\"file:\"+fileSavePath); //System.out.println(\"file:\"+fileSavePath); } }
addResourceHandler("/images/**")表示凡事以 /images/ 路径发起请求的,按照 addResourceLocations("file:"+fileSavePath)的路径进行映射
例如有一个url:http://localhost:8081/images/Hello.jpg
表示要对Hello.jpg进行请求访问,这时候服务器会把这个请求的资源映射到我们配置的路径之下 也就是会到 fileSavePath 下去寻找 是否有 Hello.jpg 这个资源,返回给前端页面。
3.Controller代码
这边为了方便使用Map进行返回,实际开发中使用封装好的类型进行返回
package com.etc.controller; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.sound.midi.SysexMessage; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @CrossOrigin @RestController public class ImgUploadController { SimpleDateFormat sdf = new SimpleDateFormat(\"/yyyy.MM.dd/\"); @Value(\"${file-save-path}\") private String fileSavePath; @PostMapping(\"/upload\") public Map<String, Object> fileupload(MultipartFile file,HttpServletRequest req){ Map<String,Object> result = new HashMap<>(); //获取文件的名字 String originName = file.getOriginalFilename(); System.out.println(\"originName:\"+originName); //判断文件类型 if(!originName.endsWith(\".jpg\")) { result.put(\"status\",\"error\"); result.put(\"msg\", \"文件类型不对\"); return result; } //给上传的文件新建目录 String format = sdf.format(new Date()); String realPath = fileSavePath + format; System.out.println(\"realPath:\"+realPath); //若目录不存在则创建目录 File folder = new File(realPath); if(! folder.exists()) { folder.mkdirs(); } //给上传文件取新的名字,避免重名 String newName = UUID.randomUUID().toString() + \".jpg\"; try { //生成文件,folder为文件目录,newName为文件名 file.transferTo(new File(folder,newName)); //生成返回给前端的url String url = req.getScheme() + \"://\" + req.getServerName() + \":\" + req.getServerPort() +\"/images\"+ format + newName; System.out.println(\"url:\"+url); //返回URL result.put(\"status\", \"success\"); result.put(\"url\", url); }catch (IOException e) { // TODO Auto-generated catch block result.put(\"status\", \"error\"); result.put(\"msg\",e.getMessage()); } return result; } }
做猪小侠源码的代理,提供一站式服务
如果你不懂得搭建网站或者服务器,小程序,源码之类的怎么办? 第一通过本站学习各种互联网的技术 第二就是联系客服,我帮帮你搭建(当然要收取部分的费用) 第三成为我们的代理,我们提供整套的服务。