利用Springboot+vue實(shí)現(xiàn)圖片上傳至數(shù)據(jù)庫并顯示的全過程
一、前端設(shè)置
前端是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在這里可以隨便設(shè)置,因?yàn)樵诤竺嬗?:http-request 去自己設(shè)置請求,注意由于是自己寫請求需要 :auto-upload=“false” ,并且由于是前后端連接要解決跨域問題,所以在 $hostURL+imageUrl 定義了一個(gè)全局變量:
//在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() //注意在這里一個(gè)坑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(); } }
在上面代碼中有一個(gè)坑 f.file ,我看了許多博客,發(fā)現(xiàn)有些博客只有 f 沒有 .file 導(dǎo)致出現(xiàn)401、505錯(cuò)誤。
二、后端代碼
1.建立數(shù)據(jù)庫
這里頭像avatar是保存的上傳圖片的部分url
2.實(shí)體類、Mapper
實(shí)體類:
采用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,采用隨機(jī)數(shù),保證每個(gè)圖片的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.后端配置
實(shí)現(xiàn)前端Vue :scr 更具url顯示頭像圖片,則必須設(shè)置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同級(jí)目錄下創(chuàng)建):
module.exports = { devServer: { // 端口號(hào) open: true, host: 'localhost', port: 8080, https: false, hotOnly: false, // 配置不同的后臺(tái)API地址 proxy: { '/api': { //后端端口號(hào) target: 'http://localhost:8082', ws: true, changOrigin: true, pathRewrite: { '^/api': '' } } }, before: app => {} } }
main.js:
axios.defaults.baseURL = '/api'
總結(jié)
到此這篇關(guān)于利用Springboot+vue實(shí)現(xiàn)圖片上傳至數(shù)據(jù)庫并顯示的文章就介紹到這了,更多相關(guān)Springboot vue圖片上傳至數(shù)據(jù)庫并顯示內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 使用Springboot+Vue實(shí)現(xiàn)文件上傳和下載功能
- 基于SpringBoot和Vue實(shí)現(xiàn)頭像上傳與回顯功能
- Vue?+?SpringBoot?實(shí)現(xiàn)文件的斷點(diǎn)上傳、秒傳存儲(chǔ)到Minio的操作方法
- springboot+vue實(shí)現(xiàn)阿里云oss大文件分片上傳的示例代碼
- Java實(shí)現(xiàn)大文件的分片上傳與下載(springboot+vue3)
- springboot整合vue2-uploader實(shí)現(xiàn)文件分片上傳、秒傳、斷點(diǎn)續(xù)傳功能
- Vue+Element+Springboot圖片上傳的實(shí)現(xiàn)示例
- Springboot+Vue-Cropper實(shí)現(xiàn)頭像剪切上傳效果
- springboot + vue+elementUI實(shí)現(xiàn)圖片上傳功能
相關(guān)文章
Solr通過特殊字符分詞實(shí)現(xiàn)自定義分詞器詳解
最近因?yàn)楣ぷ鞯男枰?,要做一個(gè)分詞器,通過查找相關(guān)的資料最終用solr實(shí)現(xiàn)了,下面這篇文章主要給大家介紹了關(guān)于Solr通過特殊字符分詞實(shí)現(xiàn)自定義分詞器的相關(guān)資料,需要的朋友可以參考借鑒,下面隨著小編來一起看看吧。2017-09-09詳細(xì)講解Java中==與equals的區(qū)別對比
這篇文章主要為大家詳細(xì)介紹了Java中==與equals的區(qū)別對比,文中有詳細(xì)的代碼示例供大家參考,具有一定的參考價(jià)值,感興趣的同學(xué)可以參考閱讀下2023-09-09關(guān)于批量插入或更新數(shù)據(jù)(MyBatis-plus框架)
這篇文章主要介紹了關(guān)于批量插入或更新數(shù)據(jù)(MyBatis-plus框架),具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09MyBatis批量更新(update foreach)報(bào)錯(cuò)問題
這篇文章主要介紹了MyBatis批量更新(update foreach)報(bào)錯(cuò)問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08SpringBoot整合RocketMq實(shí)現(xiàn)分布式事務(wù)
這篇文章主要為大家詳細(xì)介紹了SpringBoot整合RocketMq實(shí)現(xiàn)分布式事務(wù)的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考一下2024-11-11Spring Boot 中常用的注解@RequestParam及基本用法
@RequestParam 是 Spring Framework 和 Spring Boot 中常用的注解之一,用于從請求中獲取參數(shù)值,本文給大家介紹Spring Boot 中常用的注解@RequestParam,感興趣的朋友一起看看吧2023-10-10SpringBoot Devtools實(shí)現(xiàn)項(xiàng)目熱部署的方法示例
這篇文章主要介紹了SpringBoot Devtools實(shí)現(xiàn)項(xiàng)目熱部署的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01