广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot上传图片到指定位置并返回URL的实现
  • 724
分享到

SpringBoot上传图片到指定位置并返回URL的实现

2024-04-02 19:04:59 724人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录需求前端部分(ElementUI+vue.js)后端部分(SpringBoot)1.先配置application.yml文件2.映射资源-重写WEBmvcConfigurer接口

想做一个上传图片的功能,来展示用户上传的图片。

在返回给前端的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;
				
	}
}

到此这篇关于SpringBoot上传图片到指定位置并返回URL的实现的文章就介绍到这了,更多相关SpringBoot上传图片并返回URL内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot上传图片到指定位置并返回URL的实现

本文链接: https://www.lsjlt.com/news/143130.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • SpringBoot上传图片到指定位置并返回URL的实现
    目录需求前端部分(ElementUI+Vue.js)后端部分(SpringBoot)1.先配置application.yml文件2.映射资源-重写WebMvcConfigurer接口...
    99+
    2022-11-13
  • SpringBoot如何上传图片到指定位置并返回URL
    这篇文章将为大家详细讲解有关SpringBoot如何上传图片到指定位置并返回URL,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。需求前端的图片上传到服务器指定的文件目录,并且将URL返回给前端前端部分(E...
    99+
    2023-06-29
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作