Springboot2模块系列:文件模块(文件上传与下载)

1 文件大小配置

  • application.yml
spring:
  profiles: 
    active: dev
  servlet: 
    multipart: 
      max-file-size: 30MB 
      max-request-size: 30MB
  • application.properties
spring.servlet.multipart.max-file-size=30MB
spring.servlet.multipart.max-request-size=30MB

2 文件上传

2.1 单文件上传

package com.sb.controller;

import com.sb.po.PeopleInfos;
import com.sb.service.PeopleInfosService;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpStatus;

@CrossOrigin(origins="*", maxAge=3600)
@Controller
@RequestMapping("/api/ui")
public class UIController{
     
    @Autowired 
    private PeopleInfosService peopleInfosService;
    static Logger logger = LoggerFactory.getLogger(UIController.class);

    @RequestMapping(value="/single-file-upload", method=RequestMethod.POST) 
    @ResponseBody
    public Map uploadSingleFile(@RequestParam("file") MultipartFile file){
     
        Map returnMap = new HashMap();
        if(file.isEmpty()){
     
            returnMap.put("code", 400);
            returnMap.put("infos", "上传失败,请选择文件");
            return returnMap;
        }
        String fileName = file.getOriginalFilename();
        String filePath = "/home/xdq/xinPrj/java/javaWebTest/pureBackendSB/javaAI/src/main/resources/upload/";
        File fileObj = new File(filePath+fileName);
        try{
     
            // 文件保存到指定路径
            file.transferTo(fileObj);
            returnMap.put("code", 200);
            returnMap.put("infos", "上传成功");
            return returnMap;
        }catch (IOException e){
     
            e.printStackTrace();
        }
        returnMap.put("code", 400);
        returnMap.put("infos", "上传失败,请选择文件");
        return returnMap;
    }
}
  • 接口请求

Springboot2模块系列:文件模块(文件上传与下载)_第1张图片

图2.1 单文件上传

2.2 多文件上传

package com.sb.controller;

import com.sb.po.PeopleInfos;
import com.sb.service.PeopleInfosService;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpStatus;

@CrossOrigin(origins="*", maxAge=3600)
@Controller
@RequestMapping("/api/ui")
public class UIController{
     
    @Autowired 
    private PeopleInfosService peopleInfosService;
    static Logger logger = LoggerFactory.getLogger(UIController.class);
    
    @RequestMapping(value="/multi-file-upload", method=RequestMethod.POST) 
    @ResponseBody 
    public Map uploadMultiFile(HttpServletRequest req){
     
        Map returnMap = new HashMap();
        List<MultipartFile> files = ((MultipartHttpServletRequest) req).getFiles("file");
        String filePath = "/home/xdq/xinPrj/java/javaWebTest/pureBackendSB/javaAI/src/main/resources/upload/";
        for(int i=0;i<files.size();i++){
     
            MultipartFile file = files.get(i);
            if(file.isEmpty()){
     
                returnMap.put("code", 201);
                returnMap.put("infos", "上传第"+String.valueOf(i+1)+"个文件失败");
                return returnMap;
            }
            String fileName = file.getOriginalFilename();
            File fileObj = new File(filePath+fileName);
            try{
     
                file.transferTo(fileObj);
            }catch (IOException e){
     
                returnMap.put("code", 201);
                returnMap.put("infos", "上传第"+String.valueOf(i++)+"个文件失败");
                return returnMap;
            }
        }
        returnMap.put("code", 200);
        returnMap.put("infos", "上传文件失败");
        return returnMap;
    }
}
  • 接口请求

Springboot2模块系列:文件模块(文件上传与下载)_第2张图片

图2.2 多文件上传

3 文件下载

3.1 java自带文件系统

package com.sb.controller;

import com.sb.po.PeopleInfos;
import com.sb.service.PeopleInfosService;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpStatus;

@CrossOrigin(origins="*", maxAge=3600)
@Controller
@RequestMapping("/api/ui")
public class UIController{
     
    @Autowired 
    private PeopleInfosService peopleInfosService;
    static Logger logger = LoggerFactory.getLogger(UIController.class);

    @RequestMapping(value="/download", method=RequestMethod.GET) 
    @ResponseBody
    public Map downloadFile(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException{
     
        Map returnMap = new HashMap();  
        File fileDir = new File("/home/xdq/xinPrj/java/javaWebTest/pureBackendSB/javaAI/src/main/resources/upload/");
        File TrxFiles[] = fileDir.listFiles();
        logger.info("file path:{}\n", TrxFiles[0]);
        String fileName = TrxFiles[0].getName();
        logger.info("file name: {}\n", fileName);
        if(fileName != null){
     
            String realPath = "/home/xdq/xinPrj/java/javaWebTest/pureBackendSB/javaAI/src/main/resources/upload";
            File file = new File(realPath, fileName);
            if(file.exists()){
     
                res.setHeader("content-type", "application/octet-stream");
                res.setContentType("application/octet-stream");
                logger.info("文件存在\n");
                res.setContentType("application/force-download");
                res.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));
                // res.setHeader("Content-Disposition", "attachment;filename="+fileName);
                // res.setHeader("Content-Disposition", "attachment;filename="+fileName+";filename*=utf-8''");
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try{
     
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = res.getOutputStream();
                    int i = bis.read(buffer);
                    while(i!=-1){
     
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    returnMap.put("code", 200);
                    returnMap.put("infos", "下载完成");
                    return returnMap;

                }catch(Exception e){
     
                    returnMap.put("code", 400);
                    returnMap.put("infos", "下载失败");
                    return returnMap;
                }finally{
     
                    if(bis!=null){
     
                        try{
     
                            bis.close();
                        }catch(IOException e){
     
                            e.printStackTrace();
                        }
                    }
                    if(fis!=null){
     
                        try{
     
                            fis.close();
                        }catch(IOException e){
     
                            e.printStackTrace();
                        }
                    }
                }
            }else{
     
                returnMap.put("code", 400);
                returnMap.put("infos", "文件不存在,下载失败");
                return returnMap;
            }
        }else{
     
            returnMap.put("code", 400);
            returnMap.put("infos", "文件夹不存在,下载失败");
            return returnMap;
        }
        
    }
}

3.2 springframework文件系统

package com.sb.controller;

import com.sb.po.PeopleInfos;
import com.sb.service.PeopleInfosService;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpStatus;

@CrossOrigin(origins="*", maxAge=3600)
@Controller
@RequestMapping("/api/ui")
public class UIController{
     
    @Autowired 
    private PeopleInfosService peopleInfosService;
    static Logger logger = LoggerFactory.getLogger(UIController.class);
    

    @RequestMapping(value="/download-with-filename", method=RequestMethod.POST)
    public ResponseEntity<byte[]> downloadFile() throws Exception{
     
        HttpHeaders headers = null;
        ByteArrayOutputStream baos = null;
        File fileDir = new File("/home/xdq/xinPrj/java/javaWebTest/pureBackendSB/javaAI/src/main/resources/upload");
        File fileLi[] = fileDir.listFiles();
        String fileName = fileLi[0].getName();
        if(fileName != null){
     
            String realPath = "/home/xdq/xinPrj/java/javaWebTest/pureBackendSB/javaAI/src/main/resources/upload";
            File file = new File(realPath, fileName);
            headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            fis = new FileInputStream(file);
            // ByteBuffer byteBuffer = new ByteArrayBuffer();
            baos = new ByteArrayOutputStream();
            bis = new BufferedInputStream(fis);
            logger.info("buffered input stream:{}", bis);
            byte[] bytes = new byte[1024];
            logger.info("bytes: {}", bytes);
            int i = bis.read(bytes);
            while(i != -1){
     
                baos.write(bytes, 0, i);
                i = bis.read(bytes);
            }   
        }
        return new ResponseEntity<byte[]>(baos.toByteArray(), headers, HttpStatus.CREATED);
    }
}

4 web页面

  • 源码

<html>
<head>
    
    
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <title>文件上传title>
head>
<body>
    <h3>单文件上传h3>
    <form method="post" action="/api/ui/single-file-upload" enctype="multipart/form-data">
        <input type="file" name="fileName"><br>
        <input type="submit" value="提交">
    form>
    <h3>多文件上传h3>
    <form method="post" action="/api/ui/multi-file-upload" enctype="multipart/form-data">
        <p>选择文件1:<input type="file" name="fileName"/>p>
        <p>选择文件2:<input type="file" name="fileName"/>p>
        <p>选择文件3:<input type="file" name="fileName"/>p>
        <p><input type="submit" value="提交"/>p>
    form>
    <h3>文件下载h3>
    <form method="post" action="/api/ui/download-with-filename" enctype="multipart/form-data">
        <input type="submit" value="下载">
    form>
body>
html>
  • 页面

Springboot2模块系列:文件模块(文件上传与下载)_第3张图片

图4.1 文件上传/下载

【参考文献】
[1]https://www.cnblogs.com/jclian91/p/9277216.html
[2]https://www.jianshu.com/p/e678d7b362e1
[3]https://www.jianshu.com/p/be1af489551c
[4]https://blog.csdn.net/Tomwildboar/article/details/82959902

你可能感兴趣的:(#,单体服务SpringBoot2)