最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Springboot+Vue實現(xiàn)文件上傳和下載功能

 更新時間:2024年09月24日 09:26:34   作者:等雨停、  
本文介紹了如何使用Springboot結(jié)合Vue進行圖書信息管理系統(tǒng)開發(fā),包括數(shù)據(jù)庫表的創(chuàng)建,實體類、Dao層、Service層和Controller層的編寫,重點講解了文件上傳和下載功能的實現(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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot配置Clickhouse的示例代碼

    SpringBoot配置Clickhouse的示例代碼

    這篇文章主要介紹了SpringBoot配置Clickhouse的示例代碼,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考價值,需要的朋友可以參考下
    2022-02-02
  • 深度解析Java中的JSONObject從基礎(chǔ)到高級應(yīng)用

    深度解析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)自動登陸功能示例

    Spring Security實現(xiàn)自動登陸功能示例

    自動登錄在很多網(wǎng)站和APP上都能用的到,解決了用戶每次輸入賬號密碼的麻煩。本文就使用Spring Security實現(xiàn)自動登陸功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • 徹底解決java.lang.ClassNotFoundException: com.mysql.jdbc.Driver問題

    徹底解決java.lang.ClassNotFoundException: com.mysql.jdbc.Dr

    這篇文章給大家介紹了如如何徹底解決java.lang.ClassNotFoundException: com.mysql.jdbc.Driver問題,文中有詳細的解決思路以及解決方法,需要的朋友可以參考下
    2023-11-11
  • 一篇文章從無到有詳解Spring中的AOP

    一篇文章從無到有詳解Spring中的AOP

    。Spring AOP 是基于 AOP 編程模式的一個框架,它的使用有效減少了系統(tǒng)間的重復(fù)代碼,達到了模塊間的松耦合目的,這篇文章主要給大家介紹了關(guān)于Spring中AOP的相關(guān)資料,需要的朋友可以參考下
    2021-08-08
  • springboot啟動流程過程

    springboot啟動流程過程

    Spring Boot 簡化了 Spring 框架的使用,通過創(chuàng)建 `SpringApplication` 對象,判斷應(yīng)用類型并設(shè)置初始化器和監(jiān)聽器,在 `run` 方法中,讀取配置并加載到 `Environment` 中,通過 Spring 事件機制和 `EnvironmentPostProcessor` 處理配置
    2025-02-02
  • RocketMQ之Consumer整體介紹啟動源碼分析

    RocketMQ之Consumer整體介紹啟動源碼分析

    這篇文章主要為大家介紹了RocketMQ源碼分析之Consumer整體介紹啟動分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-05-05
  • Spring Security 實現(xiàn)短信驗證碼登錄功能

    Spring Security 實現(xiàn)短信驗證碼登錄功能

    這篇文章主要介紹了Spring Security 實現(xiàn)短信驗證碼登錄功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-05-05
  • Java中jqGrid 學(xué)習(xí)筆記整理——進階篇(二)

    Java中jqGrid 學(xué)習(xí)筆記整理——進階篇(二)

    這篇文章主要介紹了Java中jqGrid 學(xué)習(xí)筆記整理——進階篇(二)的相關(guān)資料,需要的朋友可以參考下
    2016-04-04
  • Spring?Boot?打包如何將依賴全部打進去

    Spring?Boot?打包如何將依賴全部打進去

    這篇文章主要介紹了Spring?Boot?打包如何將依賴全部打進去,在pom.xml中引入插件,需要在項目的pom.xml文件中,添加?Maven?插件??spring-boot-maven-plugin,本文結(jié)合實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-09-09

最新評論

平定县| 汉川市| 开平市| 苏尼特右旗| 房产| 广州市| 安宁市| 陇南市| 绍兴市| 武陟县| 新乡市| 来凤县| 高唐县| 高雄市| 军事| 阿勒泰市| 漳平市| 太仆寺旗| 哈尔滨市| 鄂托克前旗| 海宁市| 安达市| 五家渠市| 宁武县| 育儿| 万宁市| 浦北县| 电白县| 清水河县| 板桥市| 巴东县| 星子县| 嘉荫县| 克拉玛依市| 古蔺县| 望谟县| 苏尼特左旗| 石屏县| 密山市| 松潘县| 铁岭市|