SpringBoot上傳圖片到指定位置并返回URL的實現(xiàn)
想做一個上傳圖片的功能,來展示用戶上傳的圖片。
在返回給前端的URL上弄了好久,前端一直無法訪問到URL,結(jié)果一直顯示404。 倒騰了一上午發(fā)現(xiàn)是 文件路徑映射的問題,后端部分有講解決辦法,可供大家參考
需求
前端的圖片上傳到服務(wù)器指定的文件目錄,并且將URL返回給前端
前端部分(ElementUI+Vue.js)
ElementUI的導(dǎo)入和使用:(組件 | Element)
Vue.js的導(dǎo)入和使用:(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后加上 ‘\’ 導(dǎo)致路徑無法匹配到
server:
port: 8081
file-save-path: D:\SoftWare\SpringToolSuite\WorkPlace\HelloWorld\src\main\resources\static\images\
spring:
mvc:
view:
prefix: /
suffix: .jsp2.映射資源-重寫WebMvcConfigurer接口,實現(xiàn)對資源的映射
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/ 路徑發(fā)起請求的,按照 addResourceLocations("file:"+fileSavePath)的路徑進行映射
例如有一個url:http://localhost:8081/images/Hello.jpg
表示要對Hello.jpg進行請求訪問,這時候服務(wù)器會把這個請求的資源映射到我們配置的路徑之下 也就是會到 fileSavePath 下去尋找 是否有 Hello.jpg 這個資源,返回給前端頁面。
3.Controller代碼
這邊為了方便使用Map進行返回,實際開發(fā)中使用封裝好的類型進行返回
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);
//若目錄不存在則創(chuàng)建目錄
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;
}
}到此這篇關(guān)于SpringBoot上傳圖片到指定位置并返回URL的實現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot上傳圖片并返回URL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java編程一個隨機數(shù)產(chǎn)生模塊代碼分享
這篇文章主要介紹了Java編程一個隨機數(shù)產(chǎn)生模塊代碼分享,具有一定借鑒價值,需要的朋友可以參考下。2017-12-12
Spring @Primary作用和實現(xiàn)原理詳解
今天分享一下Spring中的@Primary注解,Primary的意思是主要的,我們在使用spring的時候,難免會定義多個類型相同的bean,這時候如果不采取一些方法,那么是無法正常使用bean的,所以本就給大家介紹Spring @Primary的作用和實現(xiàn)原理2023-07-07
mybatis 有時update語句執(zhí)行無效的解決方案
這篇文章主要介紹了在項目里mybatis有時update語句執(zhí)行無效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
Java實現(xiàn)郵箱發(fā)送功能實例(阿里云郵箱推送)
這篇文章主要給大家介紹了關(guān)于Java實現(xiàn)郵箱發(fā)送功能的相關(guān)資料,利用阿里云郵箱推送,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
java,android,MD5加密算法的實現(xiàn)代碼(16位,32位)
下面小編就為大家?guī)硪黄猨ava,android,MD5加密算法的實現(xiàn)代碼(16位,32位)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-09-09
SparkSQL使用IDEA快速入門DataFrame與DataSet的完美教程
本文給大家介紹使用idea開發(fā)Spark SQL 的詳細(xì)過程,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-08-08
Java實現(xiàn)一個達(dá)達(dá)租車系統(tǒng)的步驟詳解
這篇文章主要給大家介紹了利用Java實現(xiàn)一個達(dá)達(dá)租車系統(tǒng)的步驟,文中給出了詳細(xì)的實現(xiàn)思路和示例代碼,并在文末給出了完整的源碼供大家學(xué)習(xí)下載,需要的朋友可以參考借鑒,下面來一起看看吧。2017-04-04
springboot cloud使用eureka整合分布式事務(wù)組件Seata 的方法
這篇文章主要介紹了springboot cloud使用eureka整合分布式事務(wù)組件Seata 的方法 ,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05
java數(shù)據(jù)結(jié)構(gòu)和算法中哈希表知識點詳解
在本篇文章里小編給大家分享了關(guān)于java數(shù)據(jù)結(jié)構(gòu)和算法中哈希表的相關(guān)知識點內(nèi)容,需要的朋友們學(xué)習(xí)下。2019-06-06

