利用Springboot+vue實現(xiàn)圖片上傳至數(shù)據(jù)庫并顯示的全過程
一、前端設置
前端是Vue + Element-UI 采用el-upload組件(借鑒官方)上傳圖片:
<el-upload
ref="upload"
class="avatar-uploader"
action="/setimg"
:http-request="picUpload"
:show-file-list="false"
:auto-upload="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="$hostURL+imageUrl" :src="$hostURL+imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<el-button type="primary" @click="submitUpload">修改</el-button>
action在這里可以隨便設置,因為在后面有 :http-request 去自己設置請求,注意由于是自己寫請求需要 :auto-upload=“false” ,并且由于是前后端連接要解決跨域問題,所以在 $hostURL+imageUrl 定義了一個全局變量:
//在main.js中 Vue.prototype.$hostURL='http://localhost:8082'
在methods中:
methods:{
//這里是官方的方法不變
handleAvatarSuccess(res, file){
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上傳頭像圖片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上傳頭像圖片大小不能超過 2MB!');
}
return isJPG && isLt2M;
},
//這里是自定義發(fā)送請求
picUpload(f){
let params = new FormData()
//注意在這里一個坑f.file
params.append("file",f.file);
this.$axios({
method:'post',
//這里的id是我要改變用戶的ID值
url:'/setimg/'+this.userForm.id,
data:params,
headers:{
'content-type':'multipart/form-data'
}
}).then(res=>{
//這里是接受修改完用戶頭像后的JSON數(shù)據(jù)
this.$store.state.menu.currentUserInfo=res.data.data.backUser
//這里返回的是頭像的url
this.imageUrl = res.data.data.backUser.avatar
})
},
//觸發(fā)請求
submitUpload(){
this.$refs.upload.submit();
}
}
在上面代碼中有一個坑 f.file ,我看了許多博客,發(fā)現(xiàn)有些博客只有 f 沒有 .file 導致出現(xiàn)401、505錯誤。
二、后端代碼
1.建立數(shù)據(jù)庫

這里頭像avatar是保存的上傳圖片的部分url
2.實體類、Mapper
實體類:
采用mybatis plus
@Data
public class SysUser extends BaseEntity{
//這里的BaseEntity是id,statu,created,updated數(shù)據(jù)
private static final Long serialVersionUID = 1L;
@NotBlank(message = "用戶名不能為空")
private String username;
// @TableField(exist = false)
private String password;
@NotBlank(message = "用戶名稱不能為空")
private String name;
//頭像
private String avatar;
@NotBlank(message = "郵箱不能為空")
@Email(message = "郵箱格式不正確")
private String email;
private String tel;
private String address;
@TableField("plevel")
private Integer plevel;
private LocalDateTime lastLogin;
}
@Mapper
@TableName("sys_user")
public interface SysUserMapper extends BaseMapper<SysUser> {
}
3.接受請求,回傳數(shù)據(jù)
@Value("${file.upload-path}")
private String pictureurl;
@PostMapping("/setimg/{id}")
public Result setImg(@PathVariable("id") Long id, @RequestBody MultipartFile file){
String fileName = file.getOriginalFilename();
File saveFile = new File(pictureurl);
//拼接url,采用隨機數(shù),保證每個圖片的url不同
UUID uuid = UUID.randomUUID();
//重新拼接文件名,避免文件名重名
int index = fileName.indexOf(".");
String newFileName ="/avatar/"+fileName.replace(".","")+uuid+fileName.substring(index);
//存入數(shù)據(jù)庫,這里可以加if判斷
SysUser user = new SysUser();
user.setId(id);
user.setAvatar(newFileName);
sysUserMapper.updateById(user);
try {
//將文件保存指定目錄
file.transferTo(new File(pictureurl + newFileName));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("保存成功");
SysUser ret_user = sysUserMapper.selectById(user.getId());
ret_user.setPassword("");
return Result.succ(MapUtil.builder()
.put("backUser",ret_user)
.map());
}
yml文件中圖片的保存地址:
file: upload-path: D:\Study\MyAdmin\scr
三、顯示圖片
1.后端配置
實現(xiàn)前端Vue :scr 更具url顯示頭像圖片,則必須設置WebMVC中的靜態(tài)資源配置
建立WebConfig類
@Configuration
public class WebConfig implements WebMvcConfigurer{
private String filePath = "D:/Study/MyAdmin/scr/avatar/";
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/avatar/**").addResourceLocations("file:"+filePath);
System.out.println("靜態(tài)資源獲取");
}
}
這樣就可是顯示頭像圖片了
2.前端配置
注意跨域問題以及前面的全局地址變量
vue.config.js文件(若沒有則在scr同級目錄下創(chuàng)建):
module.exports = {
devServer: {
// 端口號
open: true,
host: 'localhost',
port: 8080,
https: false,
hotOnly: false,
// 配置不同的后臺API地址
proxy: {
'/api': {
//后端端口號
target: 'http://localhost:8082',
ws: true,
changOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
before: app => {}
}
}
main.js:
axios.defaults.baseURL = '/api'
總結(jié)
到此這篇關(guān)于利用Springboot+vue實現(xiàn)圖片上傳至數(shù)據(jù)庫并顯示的文章就介紹到這了,更多相關(guān)Springboot vue圖片上傳至數(shù)據(jù)庫并顯示內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 使用Springboot+Vue實現(xiàn)文件上傳和下載功能
- 基于SpringBoot和Vue實現(xiàn)頭像上傳與回顯功能
- Vue?+?SpringBoot?實現(xiàn)文件的斷點上傳、秒傳存儲到Minio的操作方法
- springboot+vue實現(xiàn)阿里云oss大文件分片上傳的示例代碼
- Java實現(xiàn)大文件的分片上傳與下載(springboot+vue3)
- springboot整合vue2-uploader實現(xiàn)文件分片上傳、秒傳、斷點續(xù)傳功能
- Vue+Element+Springboot圖片上傳的實現(xiàn)示例
- Springboot+Vue-Cropper實現(xiàn)頭像剪切上傳效果
- springboot + vue+elementUI實現(xiàn)圖片上傳功能
相關(guān)文章
Springboot項目出現(xiàn)java.lang.ArrayStoreException的異常分析
這篇文章介紹了Springboot項目出現(xiàn)java.lang.ArrayStoreException的異常分析,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-12-12
SpringMVC將請求和響應的數(shù)據(jù)轉(zhuǎn)換為JSON格式的幾種方式
這篇文章主要給大家介紹餓了SpringMVC將請求和響應的數(shù)據(jù)轉(zhuǎn)換為JSON格式的幾種方式,文中通過代碼示例和圖文結(jié)合給大家介紹的非常詳細,具有一定的參考價值,需要的朋友可以參考下2023-11-11
springboot整合mybatis中的問題及出現(xiàn)的一些問題小結(jié)
這篇文章主要介紹了springboot整合mybatis中的問題及出現(xiàn)的一些問題小結(jié),本文給出了解決方案,需要的朋友可以參考下2018-11-11
Java中實現(xiàn)Comparable和Comparator對象比較
這篇文章主要針對Java中Comparable和Comparator對象進行比較,感興趣的小伙伴們可以參考一下2016-02-02
spring-boot-maven-plugin:打包時排除provided依賴問題
這篇文章主要介紹了spring-boot-maven-plugin:打包時排除provided依賴問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04

