SpringBoot上傳圖片到指定位置并返回URL的實現(xiàn)
想做一個上傳圖片的功能,來展示用戶上傳的圖片。
在返回給前端的URL上弄了好久,前端一直無法訪問到URL,結果一直顯示404。 倒騰了一上午發(fā)現(xiàn)是 文件路徑映射的問題,后端部分有講解決辦法,可供大家參考
需求
前端的圖片上傳到服務器指定的文件目錄,并且將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: .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進行請求訪問,這時候服務器會把這個請求的資源映射到我們配置的路徑之下 也就是會到 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;
}
}到此這篇關于SpringBoot上傳圖片到指定位置并返回URL的實現(xiàn)的文章就介紹到這了,更多相關SpringBoot上傳圖片并返回URL內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決IDEA springboot"spring-boot-maven-plugin"報紅問題
這篇文章主要介紹了解決IDEA springboot"spring-boot-maven-plugin"報紅問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04
mybatisplus 的SQL攔截器實現(xiàn)關聯(lián)查詢功能
大家都知道m(xù)ybatisplus不支持關聯(lián)查詢,后來學習研究發(fā)現(xiàn)mybatisplus的SQL攔截器可以實現(xiàn)這一操作,下面小編給大家分享我的demo實現(xiàn)基本的關聯(lián)查詢功能沒有問題,對mybatisplus關聯(lián)查詢相關知識感興趣的朋友一起看看吧2021-06-06
Spring?Cloud?整合?nacos實現(xiàn)動態(tài)配置中心的詳細步驟
這篇文章主要介紹了Spring?Cloud?整合?nacos?實現(xiàn)動態(tài)配置中心,整合步驟是通過添加依賴新建nacos配置,本文分步驟通過實例代碼給大家詳細講解,需要的朋友可以參考下2022-10-10
如何對Mysql數(shù)據(jù)表查詢出來的結果進行排序
這篇文章主要介紹了如何對Mysql數(shù)據(jù)表查詢出來的結果進行排序問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08

