欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

相關(guān)文章

  • 通過源代碼分析Mybatis的功能流程詳解

    通過源代碼分析Mybatis的功能流程詳解

    這篇文章主要介紹了通過源代碼分析Mybatis的功能,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-08-08
  • Java 堆內(nèi)存溢出原因分析

    Java 堆內(nèi)存溢出原因分析

    這篇文章主要介紹了Java 堆內(nèi)存溢出原因分析,任何使用過基于 Java 的企業(yè)級后端應(yīng)用的軟件開發(fā)者都會遇到過這種報(bào)錯(cuò),java.lang.OutOfMemoryError:Java heap space。,需要的朋友可以參考下
    2019-06-06
  • Java線程之線程同步synchronized和volatile詳解

    Java線程之線程同步synchronized和volatile詳解

    這篇文章主要介紹了Java線程之線程同步synchronized和volatile詳解,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-11-11
  • 基于spring+quartz的分布式定時(shí)任務(wù)框架實(shí)現(xiàn)

    基于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)行增刪改查操作代碼實(shí)例

    這篇文章主要介紹了Java代碼對HDFS進(jìn)行增刪改查操作,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • SpringBoot 中的異步處理機(jī)制詳解

    SpringBoot 中的異步處理機(jī)制詳解

    本文介紹了異步處理的基礎(chǔ)配置、線程池的自定義以及常見應(yīng)用場景,在實(shí)際應(yīng)用中,異步處理可以有效提升應(yīng)用的性能,改善用戶體驗(yàn),但同時(shí)也需要我們合理管理線程池,確保系統(tǒng)資源的高效利用,感興趣的朋友跟隨小編一起看看吧
    2025-01-01
  • 如何基于java實(shí)現(xiàn)Gauss消元法過程解析

    如何基于java實(shí)現(xiàn)Gauss消元法過程解析

    這篇文章主要介紹了如何基于java實(shí)現(xiàn)Gauss消元法過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-10-10
  • Java基于IDEA實(shí)現(xiàn)http編程的示例代碼

    Java基于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)

    這篇文章主要介紹了如何使用spring ResponseEntity處理http響應(yīng)的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Spring如何替換掉默認(rèn)common-logging.jar

    Spring如何替換掉默認(rèn)common-logging.jar

    這篇文章主要介紹了Spring如何替換掉默認(rèn)common-logging.jar,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05

最新評論