千家信息网

SpringBoot如何上传图片到指定位置并返回URL

发表于:2026-11-04 作者:千家信息网编辑
千家信息网最后更新 2026年11月04日,这篇文章将为大家详细讲解有关SpringBoot如何上传图片到指定位置并返回URL,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。需求前端的图片上传到服务器指定的文件
千家信息网最后更新 2026年11月04日SpringBoot如何上传图片到指定位置并返回URL

这篇文章将为大家详细讲解有关SpringBoot如何上传图片到指定位置并返回URL,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

需求

前端的图片上传到服务器指定的文件目录,并且将URL返回给前端

前端部分(ElementUI+Vue.js)

ElementUI的导入和使用:(组件 | Element)

Vue.js的导入和使用:(Vue.js (vuejs.org))

效果:

后端部分(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;@Configurationpublic 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@RestControllerpublic class ImgUploadController {        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy.MM.dd/");                @Value("${file-save-path}")        private String fileSavePath;                @PostMapping("/upload")        public Map fileupload(MultipartFile file,HttpServletRequest req){                                Map 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;                                        }}

关于"SpringBoot如何上传图片到指定位置并返回URL"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

0