文件上传与下载

package com.example.demo.controller;

import com.example.demo.utils.FileUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.net.URLEncoder;
import java.util.List;

@Controller
public class FileController {

    @PostMapping(value = "/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("fileName") List<MultipartFile> fileName) {
        String file = FileUtil.getFile(fileName);
        return file;
    }
    
    //传统方法
    @GetMapping(value = "/download/{fileName}")
    @ResponseBody
    public String downloadFile(@PathVariable("fileName") String fileName, HttpServletResponse res) {

        String projectPath = System.getProperty("user.dir");

        res.setContentType("application/force-download");
        res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);

        File file = new File(projectPath+File.separator+"img"+File.separator+fileName);

        byte[] buf = new byte[1024];
        InputStream fis = null;     //读取
        OutputStream os=null;           //写入
        try {
            fis=new FileInputStream(file);
            os = res.getOutputStream();
            int count = fis.read(buf);
            while (count!=-1) {
                os.write(buf, 0, count);
                count= fis.read(buf);
            }
            System.out.println("下载成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }
    
    //springmvc独有方法
    @GetMapping(value = "/download")
    @ResponseBody
    public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException{

        String fileName="中文.png";
        String projectPath = System.getProperty("user.dir");

        File file = new File(projectPath+File.separator+"img"+File.separator+fileName);

        boolean isMSIE = FileUtil.isMSBrowser(request);
        if (isMSIE) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.OK);
    }



}

工具类

package com.example.demo.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 文件存储工具类FileUploadUtil
 */
public class FileUtil {

    public static String getFile(List<MultipartFile> file) {

        StringBuilder sb = new StringBuilder();
        String projectPath = System.getProperty("user.dir");    //获取项目的相对路径

        for (MultipartFile mf : file) {

            String fileName = mf.getOriginalFilename();    //获取文件名

            if (fileName != null && !"".equalsIgnoreCase(fileName.trim()) && fileType(fileName)) {

                File relativePath = new File(projectPath + File.separator + "img" + File.separator + System.currentTimeMillis() + "_" + fileName);
                System.out.println("上传的位置: " + projectPath + File.separator + "img");
                try {
                    mf.transferTo(relativePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                sb.append(relativePath.getName() + "\n");
            } else {
                System.out.println("格式错误");
            }
        }
        return sb.toString();
    }

    private static Boolean fileType(String fileName) {

        String[] imgType = new String[]{".jpg", ".jpeg", ".png", ".gif"};

        if (fileName == null) {
            return false;
        }
        fileName = fileName.toLowerCase();

        for (String type : imgType) {
            if (fileName.endsWith(type)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isMSBrowser(HttpServletRequest request) {
        String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};
        String userAgent = request.getHeader("User-Agent");
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal))
                return true;
        }
        return false;
    }

}

评论

暂无评论