springboot 上传于下载入门

Springboot 入门的文件上传下载

  1. 加依赖
    <dependency>
        <groupId>commons-io</groupId>K
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
    
    <!-- thymeleaf模板插件 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
    <!-- devtools插件,热部署 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
        <scope>true</scope>
    </dependency>
  1. 写上传页面
    1.  <h1 th:inlines="text">文件上传</h1>
       <form action="fileUpload" method="post" enctype="multipart/form-data">
           <p>选择文件: <input type="file" name="fileName"/></p>
           <p><input type="submit" value="上传"/></p>
       </form>
      
    2.  <h1 th:inlines="text">多文件上传</h1>
        <form action="multifileUpload" method="post" 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>
      
  2. 配置文件暂时没有
  3. Application扫面所需的包(这里只需controller)

    在这里插入图片描述
  4. 重要的来了:Controller

package com.lbl.controller;

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 javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

 @Controller
  public class FileUploadController {
     /*
     * 获取file.html页面
     */
    @RequestMapping("/file")
    public String file(){
        return "/file";//(相当于自带baseServerlet, 返回String,则是返回View地址(页面组装))
    }

/**
 * 实现文件上传
 * */
@RequestMapping("/fileUpload")
@ResponseBody
public String fileUpload(@RequestParam("fileName") MultipartFile file){
    if(file.isEmpty()){
        return "false";
    }
    String fileName = file.getOriginalFilename();
    int size = (int) file.getSize()
    System.out.println(fileName + "-->" + size);
    String path = "E:\\WorkSpace\\Idea\\sbm\\src\\main\\resources\\fileTest" ;
    File dest = new File(path + "/" + fileName);
    if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
        dest.getParentFile().mkdir();
    }
    try {
        file.transferTo(dest); //保存文件
        return "true";
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "false";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "false";
    }
}
@RequestMapping("/multifile")
public String multifile(){
    return "/multifile";
}
/**
 * 实现多文件上传
 * */
@RequestMapping(value="multifileUpload",method= RequestMethod.POST)
public @ResponseBody String multifileUpload(HttpServletRequest request){

    List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");

    if(files.isEmpty()){
        return "false";
    }

    String path = "E:\\WorkSpace\\Idea\\sbm\\src\\main\\resources\\fileTest" ;

    for(MultipartFile file:files){
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        if(file.isEmpty()){
            return "false";
        }else{
            File dest = new File(path + "/" + fileName);
            if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
                dest.getParentFile().mkdir();
            }
            try {
                file.transferTo(dest);
            }catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return "false";
            }
        }
    }
    return "上传成功!";
}
//下载请求
@RequestMapping("/download")
public String downLoad(HttpServletResponse response){
    String filename="323842288818402426.png";
    String filePath = "E:\\WorkSpace\\Idea\\sbm\\src\\main\\resources\\fileTest" ;
    File file = new File(filePath + "/" + filename);
    if(file.exists()){ //判断文件父目录是否存在
        /*设置头部*/
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment;fileName=" + filename);

        byte[] buffer = new byte[1024];
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;

        OutputStream os = null; //输出流
        try {
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while(i != -1){
                os.write(buffer);
                i = bis.read(buffer);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("----------file download" + filename);
        try {
            bis.close();
            fis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return "文件不存在!下载失败!";
}

}
6.文件上传页面显示
上传页面
下载就是发请求(这里问价是写好的纯测试下载功能,其实下载操作一般要显示个文件名(做链接),再去文件里面读取下载)
下载这里就是直接发请求

7.差不多就这样了,第一个博客,略显粗糙。。。再接再励

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值