SoFunction
Updated on 2025-03-01

Use Springboot+Vue to implement file upload and download functions

Addition, deletion, modification and search of book information management

Create a database table

CREATE TABLE `book` (
    `id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key ID',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Book Name',
`price` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Book Price',
`author` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Book Author',
`press` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Book Publishing House',
`img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Book Cover',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Create entity class

@Table(name = "book")
public class Book {
    @Id
    @GeneratedValue(strategy = )
    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;
}

import ;
import ;
import ;
import ;
import ;
import ;
@Repository
public interface BookDao extends Mapper<Book> {
    List<Book> findBySearch(@Param("params") Params params);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/">
<mapper namespace="">
<select  resultType="">
select * from book
<where>
<if test="params != null and  != null and  != ''">
and name like concat('%', #{  }, '%')
</if>
<if test="params != null and  != null and  != ''">
and author like concat('%', #{  }, '%')
</if>
</where>
</select>
</mapper>

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@Service
public class BookService {
    @Resource
    private BookDao bookDao;
    public PageInfo&lt;Book&gt; findBySearch(Params params) {
        // Turn on paging query        ((), ());
        // The next query will automatically query according to the currently enabled paging settings        List&lt;Book&gt; list = (params);
        return (list);
    }
    public void add(Book book) {
        (book);
    }
    public void update(Book book) {
        (book);
    }
    public void delete(Integer id) {
        (id);
    }
}

import ;
import ;
import ;
import ;
import ;
import .*;
import ;
@CrossOrigin
@RestController
@RequestMapping("/book")
public class BookController {
    @Resource
    private BookService bookService;
    @GetMapping("/search")
    public Result findBySearch(Params params) {
        PageInfo<Book> info = (params);
        return (info);
    }
    @PostMapping
    public Result save(@RequestBody Book book) {
        if (() == null) {
            (book);
        } else {
            (book);
        }
        return ();
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        (id);
        return ();
    }
}

Upload book cover file

package ;
import ;
import ;
import ;
import .*;
import ;
import ;
import ;
import ;
import ;
/**
  * File upload interface
  */
@RestController
@RequestMapping("/files")
public class FileController {
    // File upload storage path    private static final String filePath = ("") + "/file/";
    /**
      * File upload
      */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        synchronized () {
            String flag = () + "";
            String fileName = ();
            try {
                if (!(filePath)) {
                    (filePath);
                }
                // File storage form: timestamp - file name                ((), filePath + flag + "-" + fileName);
                (fileName + "--Uploaded successfully");
                (1L);
            } catch (Exception e) {
                (fileName + "--File upload failed");
            }
            return (flag);
        }
    }
    /**
      * Get the file
      */
    @GetMapping("/{flag}")
    public void avatarPath(@PathVariable String flag, HttpServletResponse response) {
        if (!(filePath)) {
            (filePath);
        }
        OutputStream os;
        List&lt;String&gt; fileNames = (filePath);
        String avatar = ().filter(name -&gt; (flag)).findAny().orElse("");
        try {
            if ((avatar)) {
                ("Content-Disposition", "attachment;filename=" + (avatar, "UTF-8"));
                ("application/octet-stream");
                byte[] bytes = (filePath + avatar);
                os = ();
                (bytes);
                ();
                ();
            }
        } catch (Exception e) {
            ("File download failed");
        }
    }
}

The upload and download interface cannot be intercepted, and it needs to be released.

// Add a custom interceptor JwtInterceptor to set interception rules@Override
public void addInterceptors(InterceptorRegistry registry) {
(jwtInterceptor).addPathPatterns("/api/**")
.excludePathPatterns("/api/files/**")
.excludePathPatterns("/api/admin/login")
.excludePathPatterns("/api/admin/register");
}

el-upload:Element - The world's most popular Vue UI framework

&lt;el-form-item label="Book Cover" label-width="20%"&gt;
&lt;el-upload action="http://localhost:8080/api/files/upload" :on-success="successUpload"&gt;
&lt;el-button size="small" type="primary"&gt;Click to upload&lt;/el-button&gt;
&lt;/el-upload&gt;
&lt;/el-form-item&gt;
successUpload(res) {
     = ;
},

Book cover preview and download

el-image:Element - The world's most popular Vue UI framework

&lt;el-table-column label="Book Cover"&gt;
&lt;template v-slot="scope"&gt;
&lt;el-image
style="width: 70px; height: 70px; border-radius: 50%"
:src="'http://localhost:8080/api/files/' + "
:preview-src-list="['http://localhost:8080/api/files/' + ]"&gt;
&lt;/el-image&gt;
&lt;/template&gt;
&lt;/el-table-column&gt;
&lt;el-button type="primary" @click="down()"&gt;download&lt;/el-button&gt;
down(flag) {
     = 'http://localhost:8080/api/files/' + flag
}

This is the article about using Springboot+Vue to upload and download files. For more related Springboot Vue file upload and download content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!