使用Springboot+Vue實現(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 '圖書價格',
`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)建實體類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)前開啟的分頁設(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);
}
// 文件存儲形式:時間戳-文件名
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">點擊上傳</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實現(xiàn)文件上傳和下載的文章就介紹到這了,更多相關(guān)Springboot Vue文件上傳和下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guā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ù)傳功能
- 利用Springboot+vue實現(xiàn)圖片上傳至數(shù)據(jù)庫并顯示的全過程
- Vue+Element+Springboot圖片上傳的實現(xiàn)示例
- Springboot+Vue-Cropper實現(xiàn)頭像剪切上傳效果
- springboot + vue+elementUI實現(xiàn)圖片上傳功能
相關(guān)文章
深度解析Java中的JSONObject從基礎(chǔ)到高級應(yīng)用
在當(dāng)今前后端分離的架構(gòu)中,JSONObject已成為Java開發(fā)者處理JSON數(shù)據(jù)的瑞士軍刀,本文將深入解析JSONObject的核心機制與實戰(zhàn)技巧,感興趣的朋友跟隨小編一起看看吧2025-09-09
Spring Security實現(xiàn)自動登陸功能示例
自動登錄在很多網(wǎng)站和APP上都能用的到,解決了用戶每次輸入賬號密碼的麻煩。本文就使用Spring Security實現(xiàn)自動登陸功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11
徹底解決java.lang.ClassNotFoundException: com.mysql.jdbc.Dr
這篇文章給大家介紹了如如何徹底解決java.lang.ClassNotFoundException: com.mysql.jdbc.Driver問題,文中有詳細的解決思路以及解決方法,需要的朋友可以參考下2023-11-11
Spring Security 實現(xiàn)短信驗證碼登錄功能
這篇文章主要介紹了Spring Security 實現(xiàn)短信驗證碼登錄功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05
Java中jqGrid 學(xué)習(xí)筆記整理——進階篇(二)
這篇文章主要介紹了Java中jqGrid 學(xué)習(xí)筆記整理——進階篇(二)的相關(guān)資料,需要的朋友可以參考下2016-04-04

