springboot2.0 文件上传下载

页面

 <h2>上传文件sss</h2>
    <form action="/file/upload" method="post" enctype="multipart/form-data" >
        <!--<input  type="file" name="myfile" method="post" action="localfile/upload"/><br>-->
        <!--<input type="submit" value="提交"/>-->

        <input type="file" name="myfile"/><br/>
        <input  type="submit" value="提交"/>

    </form>
    <h1>文件下载</h1>
    <a href="/file/download">下载</a>

controller:

package com.springboot2.thyemleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * Created by  lpw'ASUS on 2018/5/30.
 */
@Controller
@RequestMapping("/file")
public class MyfileCOntroller {

    @RequestMapping("upload")
    @ResponseBody
    public String getfile(@RequestParam("myfile") MultipartFile file){
        System.out.println("file name = "+file.getOriginalFilename());

        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 文件上产的路径
        String filePath = "d:/upload/";
        // fileName处理
        fileName = filePath+ UUID.randomUUID()+fileName;
        // 文件对象
        File dest = new File(fileName);
        // 创建路径
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "上传失败";
    }

    @RequestMapping("download")
    public void download(HttpServletResponse response) throws FileNotFoundException {
        File file =new File("C:\\Users\\ASUS\\Desktop\\spring-boot-reference.pdf");
        FileInputStream fileInputStream=new FileInputStream(file);
        // 设置被下载而不是被打开
        response.setContentType("application/gorce-download");
        // 设置被第三方工具打开,设置下载的文件名
        response.addHeader("Content-disposition","attachment;fileName=spring-boot-reference.pdf");
        try {
            OutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

设置上传的大小

application.properties

#最大文件大小。值可以使用后缀“MB”或“KB”。指示兆字节或千字节大小。
spring.servlet.multipart.max-file-size=10MB
# 最大请求大小可以是mb也可以是kb
spring.servlet.multipart.max-request-size=10MB

猜你喜欢

转载自blog.csdn.net/m0_38044453/article/details/80511981