spring boot 实现文件上传和下载

 

文件上传

创建spring boot项目,在static目录下创建html页面(此时可直接访问localhost:端口号)

 

(如果将页面建立在templates文件夹中,需要引入thymeleaf依赖,然后在controller中添加方法跳转至页面,方法名为页面名称,如下:)

 


控制层:
package com.daqsoft.demo;

import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * @Description Created by liaoxx on 2017-6-1.
 */
@Controller
@RequestMapping("test")
public class UploadController {
    /**
     * 单文件上传
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //文件上传路径
            String filePath = "e:/upload/";
            // 解决中文问题,liunx下中文路径,图片显示问题
            fileName = UUID.randomUUID() + suffixName;
            File dest = new File(filePath + fileName);
            //检测是否存在上传目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败";
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败";
            }
            return "上传成功";
        } else {
            return "上传失败,上传文件为空!";
        }
    }


    /**
     * 多文件上传
     * @param request
     * @return
     */
    @RequestMapping(value = "/batchUpload",method = RequestMethod.POST)
    @ResponseBody
    public String batchUpload(HttpServletRequest request){
        List<MultipartFile> fileList = ((MultipartHttpServletRequest)request).getFiles("file");
        for (MultipartFile file : fileList) {
            fileUpload(file);
        }
        return "上传成功!";
    }

    /**
     * 页面在templates文件夹下时,访问此方法可进入页面,
     * 在static文件夹时,直接访问即可
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return "/index";
    }
}

 

 

文件下载

 

控制器:

package com.daqsoft.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Description Created by liaoxx on 2017-6-1.
 */
@Controller
@RequestMapping("down")
public class DownloadController {
    @RequestMapping(value="/download",method= RequestMethod.GET)
    public void testDownload(HttpServletResponse resp) throws IOException {
        //下载路径
        File file = new File("e:/Jellyfish.jpg");
        resp.setHeader("content-type", "application/octet-stream");
        //指明文件类型
        resp.setContentType("application/octet-stream");
        resp.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            while (bis.read(buff) != -1) {
              os.write(buff, 0, buff.length);
              os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(os!=null){
                    os.close();
                }
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

 

 

 

posted on 2017-06-01 16:18  Sunday_xiao  阅读(162)  评论(0)    收藏  举报