Spring Boot 文件上传与下载

package org.hostcoz.web.controller;

import jdk.internal.util.xml.impl.Input;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.jni.Multicast;
import org.colacloud.dto.FileInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {
    String folder = "C:\\Users\\xiaodao\\Desktop\\ColaCloudSecurity\\colacloud-demo\\src\\main\\java\\org\\colacloud\\web\\controller";

    @PostMapping
    public FileInfo upload(MultipartFile file) throws IOException {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());
        File localFile = new File(folder,new Date().getTime()+".txt");
        file.transferTo(localFile);
        return new FileInfo(localFile.getAbsolutePath());
    }
    @GetMapping("/{id}")
    public void download(@PathVariable String  id, HttpServletRequest request, HttpServletResponse response){
        try (
                InputStream inputStream = new FileInputStream(new File(folder,id+".txt"));
                OutputStream outputStream =response.getOutputStream();
                ){
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition","attachment;filename=test.txt");
            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

原文链接:,转发请注明来源!

发表评论

  • 2 Responses to “Spring Boot 文件上传与下载”