使用Springboot+Vue實(shí)現(xiàn)文件上傳和下載功能
圖書信息管理的增刪改查
創(chuàng)建數(shù)據(jù)庫表
CREATE TABLE `book` ( `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主鍵ID', `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '圖書名稱', `price` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '圖書價(jià)格', `author` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '圖書作者', `press` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '圖書出版社', `img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '圖書封面', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
創(chuàng)建實(shí)體類Book.java
@Table(name = "book") public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "name") private String name; @Column(name = "price") private String price; @Column(name = "author") private String author; @Column(name = "press") private String press; @Column(name = "img") private String img; }
BookDao.java BookMapper.xml
import com.example.entity.Book; import com.example.entity.Params; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import tk.mybatis.mapper.common.Mapper; import java.util.List; @Repository public interface BookDao extends Mapper<Book> { List<Book> findBySearch(@Param("params") Params params); }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.dao.BookDao"> <select id="findBySearch" resultType="com.example.entity.Book"> select * from book <where> <if test="params != null and params.name != null and params.name != ''"> and name like concat('%', #{ params.name }, '%') </if> <if test="params != null and params.author != null and params.author != ''"> and author like concat('%', #{ params.author }, '%') </if> </where> </select> </mapper>
BookService.java
import com.example.dao.BookDao; import com.example.entity.Book; import com.example.entity.Params; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class BookService { @Resource private BookDao bookDao; public PageInfo<Book> findBySearch(Params params) { // 開啟分頁查詢 PageHelper.startPage(params.getPageNum(), params.getPageSize()); // 接下來的查詢會自動(dòng)按照當(dāng)前開啟的分頁設(shè)置來查詢 List<Book> list = bookDao.findBySearch(params); return PageInfo.of(list); } public void add(Book book) { bookDao.insertSelective(book); } public void update(Book book) { bookDao.updateByPrimaryKeySelective(book); } public void delete(Integer id) { bookDao.deleteByPrimaryKey(id); } }
BookController.java
import com.example.common.Result; import com.example.entity.Book; import com.example.entity.Params; import com.example.service.BookService; import com.github.pagehelper.PageInfo; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @CrossOrigin @RestController @RequestMapping("/book") public class BookController { @Resource private BookService bookService; @GetMapping("/search") public Result findBySearch(Params params) { PageInfo<Book> info = bookService.findBySearch(params); return Result.success(info); } @PostMapping public Result save(@RequestBody Book book) { if (book.getId() == null) { bookService.add(book); } else { bookService.update(book); } return Result.success(); } @DeleteMapping("/{id}") public Result delete(@PathVariable Integer id) { bookService.delete(id); return Result.success(); } }
圖書封面文件上傳
FileController.java
package com.example.controller; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.StrUtil; import com.example.common.Result; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.net.URLEncoder; import java.util.List; /** * 文件上傳接口 */ @RestController @RequestMapping("/files") public class FileController { // 文件上傳存儲路徑 private static final String filePath = System.getProperty("user.dir") + "/file/"; /** * 文件上傳 */ @PostMapping("/upload") public Result upload(MultipartFile file) { synchronized (FileController.class) { String flag = System.currentTimeMillis() + ""; String fileName = file.getOriginalFilename(); try { if (!FileUtil.isDirectory(filePath)) { FileUtil.mkdir(filePath); } // 文件存儲形式:時(shí)間戳-文件名 FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName); System.out.println(fileName + "--上傳成功"); Thread.sleep(1L); } catch (Exception e) { System.err.println(fileName + "--文件上傳失敗"); } return Result.success(flag); } } /** * 獲取文件 */ @GetMapping("/{flag}") public void avatarPath(@PathVariable String flag, HttpServletResponse response) { if (!FileUtil.isDirectory(filePath)) { FileUtil.mkdir(filePath); } OutputStream os; List<String> fileNames = FileUtil.listFileNames(filePath); String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse(""); try { if (StrUtil.isNotEmpty(avatar)) { response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8")); response.setContentType("application/octet-stream"); byte[] bytes = FileUtil.readBytes(filePath + avatar); os = response.getOutputStream(); os.write(bytes); os.flush(); os.close(); } } catch (Exception e) { System.out.println("文件下載失敗"); } } }
上傳下載接口不能攔截,需要放行
// 加自定義攔截器JwtInterceptor,設(shè)置攔截規(guī)則 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(jwtInterceptor).addPathPatterns("/api/**") .excludePathPatterns("/api/files/**") .excludePathPatterns("/api/admin/login") .excludePathPatterns("/api/admin/register"); }
BookView.vue
el-upload:Element - The world's most popular Vue UI framework
<el-form-item label="圖書封面" label-width="20%"> <el-upload action="http://localhost:8080/api/files/upload" :on-success="successUpload"> <el-button size="small" type="primary">點(diǎn)擊上傳</el-button> </el-upload> </el-form-item>
successUpload(res) { this.form.img = res.data; },
圖書封面預(yù)覽、下載
el-image:Element - The world's most popular Vue UI framework
<el-table-column label="圖書封面"> <template v-slot="scope"> <el-image style="width: 70px; height: 70px; border-radius: 50%" :src="'http://localhost:8080/api/files/' + scope.row.img" :preview-src-list="['http://localhost:8080/api/files/' + scope.row.img]"> </el-image> </template> </el-table-column> <el-button type="primary" @click="down(scope.row.img)">下載</el-button>
down(flag) { location.href = 'http://localhost:8080/api/files/' + flag }
到此這篇關(guān)于使用Springboot+Vue實(shí)現(xiàn)文件上傳和下載的文章就介紹到這了,更多相關(guān)Springboot Vue文件上傳和下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 基于SpringBoot和Vue實(shí)現(xiàn)頭像上傳與回顯功能
- Vue?+?SpringBoot?實(shí)現(xiàn)文件的斷點(diǎn)上傳、秒傳存儲到Minio的操作方法
- springboot+vue實(shí)現(xiàn)阿里云oss大文件分片上傳的示例代碼
- Java實(shí)現(xiàn)大文件的分片上傳與下載(springboot+vue3)
- springboot整合vue2-uploader實(shí)現(xiàn)文件分片上傳、秒傳、斷點(diǎn)續(xù)傳功能
- 利用Springboot+vue實(shí)現(xiàn)圖片上傳至數(shù)據(jù)庫并顯示的全過程
- Vue+Element+Springboot圖片上傳的實(shí)現(xiàn)示例
- Springboot+Vue-Cropper實(shí)現(xiàn)頭像剪切上傳效果
- springboot + vue+elementUI實(shí)現(xiàn)圖片上傳功能
相關(guān)文章
Java線程之線程同步synchronized和volatile詳解
這篇文章主要介紹了Java線程之線程同步synchronized和volatile詳解,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11基于spring+quartz的分布式定時(shí)任務(wù)框架實(shí)現(xiàn)
在Spring中的定時(shí)任務(wù)功能,最好的辦法當(dāng)然是使用Quartz來實(shí)現(xiàn)。這篇文章主要介紹了基于spring+quartz的分布式定時(shí)任務(wù)框架實(shí)現(xiàn),有興趣的可以了解一下。2017-01-01編寫Java代碼對HDFS進(jìn)行增刪改查操作代碼實(shí)例
這篇文章主要介紹了Java代碼對HDFS進(jìn)行增刪改查操作,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04如何基于java實(shí)現(xiàn)Gauss消元法過程解析
這篇文章主要介紹了如何基于java實(shí)現(xiàn)Gauss消元法過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10Java基于IDEA實(shí)現(xiàn)http編程的示例代碼
這篇文章主要介紹了Java基于IDEA實(shí)現(xiàn)http編程的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04如何使用spring ResponseEntity處理http響應(yīng)
這篇文章主要介紹了如何使用spring ResponseEntity處理http響應(yīng)的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07Spring如何替換掉默認(rèn)common-logging.jar
這篇文章主要介紹了Spring如何替換掉默認(rèn)common-logging.jar,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05