SpringBoot+Vue.js實(shí)現(xiàn)前后端分離的文件上傳功能
這篇文章需要一定Vue和SpringBoot的知識(shí),分為兩個(gè)項(xiàng)目,一個(gè)是前端Vue項(xiàng)目,一個(gè)是后端SpringBoot項(xiàng)目。
后端項(xiàng)目搭建
我使用的是SpringBoot1.5.10+JDK8+IDEA 使用IDEA新建一個(gè)SpringBoot項(xiàng)目,一直點(diǎn)next即可
項(xiàng)目創(chuàng)建成功后,maven的pom配置如下
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!--加入web模塊--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.39</version> </dependency> </dependencies>
接下來(lái)編寫上傳的API接口
@RestController @RequestMapping("/upload") @CrossOrigin public class UploadController { @Value("${prop.upload-folder}") private String UPLOAD_FOLDER; private Logger logger = LoggerFactory.getLogger(UploadController.class); @PostMapping("/singlefile") public Object singleFileUpload(MultipartFile file) { logger.debug("傳入的文件參數(shù):{}", JSON.toJSONString(file, true)); if (Objects.isNull(file) || file.isEmpty()) { logger.error("文件為空"); return "文件為空,請(qǐng)重新上傳"; } try { byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename()); //如果沒(méi)有files文件夾,則創(chuàng)建 if (!Files.isWritable(path)) { Files.createDirectories(Paths.get(UPLOAD_FOLDER)); } //文件寫入指定路徑 Files.write(path, bytes); logger.debug("文件寫入成功..."); return "文件上傳成功"; } catch (IOException e) { e.printStackTrace(); return "后端異常..."; } } }
CrossOrigin注解:解決跨域問(wèn)題,因?yàn)榍昂蠖送耆蛛x,跨域問(wèn)題在所難免,加上這個(gè)注解會(huì)讓Controller支持跨域,如果去掉這個(gè)注解,前端Ajax請(qǐng)求不會(huì)到后端。這只是跨域的一種解決方法,還有其他解決方法這篇文章先不涉及。
MultipartFile:SpringMVC的multipartFile對(duì)象,用于接收前端請(qǐng)求傳入的FormData。
PostMapping是Spring4.3以后引入的新注解,是為了簡(jiǎn)化HTTP方法的映射,相當(dāng)于我們常用的@RequestMapping(value = "/xx", method = RequestMethod.POST).
后端至此已經(jīng)做完了,很簡(jiǎn)單。
前端項(xiàng)目搭建
我使用的是Node8+Webpack3+Vue2
本地需要安裝node環(huán)境,且安裝Vue-cli,使用Vue-cli生成一個(gè)Vue項(xiàng)目。
項(xiàng)目創(chuàng)建成功之后,用WebStorm打開(kāi),就可以寫一個(gè)簡(jiǎn)單的上傳例子了,主要代碼如下:
<template> <div class="hello"> <h1>{{ msg }}</h1> <form> <input type="file" @change="getFile($event)"> <button class="button button-primary button-pill button-small" @click="submit($event)">提交</button> </form> </div> </template> <script> import axios from 'axios'; export default { name: 'HelloWorld', data() { return { msg: 'Welcome to Your Vue.js App', file: '' } }, methods: { getFile: function (event) { this.file = event.target.files[0]; console.log(this.file); }, submit: function (event) { //阻止元素發(fā)生默認(rèn)的行為 event.preventDefault(); let formData = new FormData(); formData.append("file", this.file); axios.post('http://localhost:8082/upload/singlefile', formData) .then(function (response) { alert(response.data); console.log(response); window.location.reload(); }) .catch(function (error) { alert("上傳失敗"); console.log(error); window.location.reload(); }); } } } </script>
使用Axios向后端發(fā)送Ajax請(qǐng)求,使用H5的FormData對(duì)象封裝圖片數(shù)據(jù)
測(cè)試
啟動(dòng)服務(wù)端,直接運(yùn)行BootApplication類的main方法,端口8082
啟動(dòng)前端,端口默認(rèn)8080,cd到前端目錄下,分別執(zhí)行:
npm install npm run dev
啟動(dòng)成功后訪問(wèn)localhost:8080
選擇一張圖片上傳,可以看到,上傳成功之后,后端指定目錄下也有了圖片文件
總結(jié)
到這里,一個(gè)前后端分離的上傳demo就做完了,本篇文章是一個(gè)簡(jiǎn)單的demo,只能應(yīng)對(duì)小文件的上傳,后面我將會(huì)寫一篇SpringBoot+Vue實(shí)現(xiàn)大文件分塊上傳,敬請(qǐng)期待。 附上源碼,歡迎star:boot-upload 。
相關(guān)文章
springboot大文件上傳、分片上傳、斷點(diǎn)續(xù)傳、秒傳的實(shí)現(xiàn)
本文主要介紹了springboot大文件上傳、分片上傳、斷點(diǎn)續(xù)傳、秒傳的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07mybatis報(bào)錯(cuò)?resultMapException的解決
這篇文章主要介紹了mybatis報(bào)錯(cuò)?resultMapException的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01Java利用多線程和分塊實(shí)現(xiàn)快速讀取文件
在工作中經(jīng)常會(huì)有接收文件并且讀取落庫(kù)的需求,讀取方式都是串行讀取,所以本文主要為大家介紹一下如何利用多線程和分塊實(shí)現(xiàn)快速讀取文件,希望對(duì)大家有所幫助2023-09-09Java實(shí)現(xiàn)導(dǎo)入導(dǎo)出Excel文件的方法(poi,jxl)
這篇文章主要介紹了Java實(shí)現(xiàn)導(dǎo)入導(dǎo)出Excel文件的方法(poi,jxl),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08