SpringBoot上传文件到后端服务器

x33g5p2x  于2022-02-07 转载在 Spring  
字(3.7k)|赞(0)|评价(0)|浏览(239)

定义上传文件的服务:

import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Path;

public interface StorageService {
    long save(MultipartFile file, String dst) throws Exception;

    void deleteAll(Path path);
}

上传服务的接口实现:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

@Service
public class FileSystemStorageService implements StorageService {
    @Autowired
    public FileSystemStorageService() {

    }

    @Override
    public long save(MultipartFile file, String uploadFilePath) throws Exception {
        if (file.isEmpty()) {
            throw new Exception("Failed to store empty file " + file.getOriginalFilename());
        }

        if (!Files.exists(Path.of(uploadFilePath))) {
            try {
                Files.createDirectory(Path.of(uploadFilePath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String filePath = uploadFilePath + file.getOriginalFilename();
        File dest = new File(filePath);

        long cnt = 0;
        try {
            cnt = Files.copy(file.getInputStream(), dest.toPath());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return cnt;
    }

    @Override
    public void deleteAll(Path rootLocation) {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }
}

上面是基础的上传服务,写好后,开始写spring boot的controller控制器:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Path;

@Controller
public class FileUploadController {
    private final StorageService storageService;

    @Value("${file.upload.path}")
    private String uploadFilePath;

    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("/upload_page")
    public String uploadPage() {
        //返回存放在resources/templates下面的my_file_upload.html文件。
        return "my_file_upload.html";
    }

    //触发动作对应my_file_upload.html里面的form表单中的action
    @PostMapping("/do_upload_action")
    @ResponseBody
    public String uploadFiles(@RequestPart MultipartFile file) {
        String fileName = file.getOriginalFilename();
        System.out.println("开始上传文件 " + fileName);

        long cnt = 0;
        try {
            cnt = storageService.save(file, uploadFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "上传字节数 " + cnt;
    }

    @GetMapping("/delete_file")
    @ResponseBody
    public String deleteFile() {
        storageService.deleteAll(Path.of(uploadFilePath));
        return "删除完成";
    }
}

在FileUploadController里面用到了my_file_upload.html,my_file_upload.html需要放在resources/templates下面,my_file_upload.html代码内容:

<html>
<body>
<form method="post" action="/do_upload_action" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <hr>
    <input type="submit" value="提交上传">
</form>
</body>
</html>

my_file_upload.html里面的action="/do_upload_action"对应于FileUploadController中的uploadFiles()函数。

最后,在application.properties里面定义默认的上传文件目录,这个路径是服务器的位置,即当浏览器(客户端)上传文件后,保存到application.properties定义的服务器上的这个文件目录下面。

file.upload.path=E:/web/

application类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringUploadfileApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringUploadfileApplication.class, args);
    }
}

至此完成。

下面测试,在浏览器输入地址 http://localhost:8080/upload_page

服务器返回(浏览器出现)my_file_upload.html内容。随后选择一个文件,提交上传,浏览器页面跳转到 http://localhost:8080/do_upload_action

上传成功后,服务器返回上传文件的总字节数。

若直接在浏览器访问 http://localhost:8080/delete_file

就会删除定义的服务器端文件存储目录所有内容。

相关文章