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

作者:七旅之言 时间:2023-08-13 14:02:52 

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

在返回给前端的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上传图片到指定位置并返回URL的实现

后端部分(SpringBoot)

1.先配置application.yml文件

file-save-path:要保存图片的位置 早上遇到404问题是因为 在 配置file-save-path时候 没有在最后的 images后加上 &lsquo;\&rsquo; 导致路径无法匹配到

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;

}
}

来源:https://juejin.cn/post/7076317784325488648

标签:SpringBoot,上传图片,返回URL
0
投稿

猜你喜欢

  • 一场由Java中Integer引发的踩坑实战

    2021-09-06 11:14:40
  • RN在Android打包发布App(详解)

    2021-08-25 06:21:11
  • c# 实现汉诺塔游戏

    2022-11-21 01:02:57
  • 简单了解SpringCloud运行原理

    2023-06-09 17:07:15
  • Android中Bitmap常见的一些操作:缩放、裁剪、旋转和偏移

    2023-10-06 18:24:32
  • 轻松学习C#的属性

    2022-07-21 06:24:04
  • Android拍照上传功能示例代码

    2022-08-22 07:51:39
  • Android 6.0指纹识别App开发案例

    2021-06-05 10:30:07
  • CAD2008+VS2008开发ObjectARX加载失败问题(推荐)

    2023-11-06 00:36:46
  • MyBatis Xml映射文件之字符串替换方式

    2022-03-23 00:06:39
  • 属于自己的Android对话框(Dialog)自定义集合

    2022-08-03 23:09:21
  • springcloud初体验(真香)

    2022-12-08 06:33:44
  • C#判断多个文本框是否为空的方法

    2022-05-12 23:05:32
  • C#语言主要特性总结

    2021-07-16 07:59:43
  • 详解Asp.Net MVC的Bundle捆绑

    2021-09-10 05:21:38
  • 通过源码角度看看AccessibilityService

    2023-07-25 09:31:43
  • C#开发WPF程序中的弱事件模式

    2022-11-21 12:50:34
  • 在C#使用字典存储事件示例及实现自定义事件访问器

    2022-08-14 14:34:52
  • Java用单向环形链表来解决约瑟夫环Josepfu问题

    2023-03-13 18:54:20
  • C#抓取当前屏幕并保存为图片的方法

    2023-09-27 08:39:43
  • asp之家 软件编程 m.aspxhome.com