Spring Boot 文件操作,上傳、瀏覽和刪除


視頻演示: https://www.bilibili.com/video/BV1rv411B7fs/

一起來完成以下步驟:

該工程演示Spring Boot如何上傳、展示和刪除文件

  1. 頁面引擎采用Thymeleaf
  2. 后端使用Spring Boot
  3. 文件上傳使用Form提交方式(而不是Ajax方式或VUE前后端分離)

#FileControlle.java

package com.deepincoding.fileuploadformpage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class FileController {

    //上傳文件路徑
    @Value("${file.base.director}")
    private String fileBaseDirector;
    private Path fileBasePath;

    @Autowired
    private void createDirectories(){
        try {
            Files.createDirectories(Paths.get(fileBaseDirector));
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.fileBasePath = Path.of(fileBaseDirector);
    }

    /** * 首頁 * @return */
    @GetMapping("/")
    public String index(){
        return "index";
    }

    /** * 上傳頁面 * @return */
    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }

    /** * 獲取文件列表 * @return * @throws IOException */
    @GetMapping("/files")
    public String files(Model model) throws IOException {
        List<FileObject> filesAll = Files.walk(fileBasePath,1)
                .filter(path -> !path.equals(fileBasePath))
                .map(path -> {
                    String url = MvcUriComponentsBuilder.fromMethodName(FileController.class,"loadFile",path.getFileName().toString()).build().toString();
                    FileObject  fileObject = new FileObject(path.getFileName().toString(),url);
                    return fileObject;
                }).collect(Collectors.toList());
        model.addAttribute("files",filesAll);
        return "files";
    }

    /** * 刪除文件 * @param fileName * @return */
    @GetMapping("/delete/{fileName}")
    public String deleteFile(@PathVariable String fileName){
        Path deletePath = fileBasePath.resolve(fileName);
        Boolean isDelete = Boolean.FALSE;
        try {
            isDelete = FileSystemUtils.deleteRecursively(deletePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/files";
    }

    
    /** * 上傳文件事件 * @param file * @return */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file){
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        Path path = Path.of(fileBaseDirector + fileName);
        try {
            Files.copy(file.getInputStream(),path,StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/files";
    }


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM