SpringMvc(文件上传&下载)

1、文件下载

1.1、基于servlet api的文件下载

package cool.ale.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author dujlc
 */
@Controller
public class DownLoadController {
    /**
     * 基于servlet api的文件下载
     */
    @RequestMapping("/download01")
    public String download01(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取当前项目路径下的下载文件(真是开发中文件名肯定是从数据中读取的)
        String realPath = request.getServletContext().getRealPath("/file/fengjing.jpg");
        // 根据文件路径封装成了File对象
        File tmpFile = new File(realPath);
        // 可以直接根据File对象获取文件名
        String fileName = tmpFile.getName();
        // 设置响应头 content-disposition : 就是设置文件下载的打开方式,默认会在网页上打开
        // 设置 attachment;filename= 就是为了以下下载方式来打开文件
        // 如果不设置 attachment; 值,就不会下载文件,则会将文件展示到浏览器的另外一个窗口
        // "UTF-8"设置如果文件名有中心就不会乱码
        response.addHeader("Content-Disposition","attachment;filename="
                + URLEncoder.encode(fileName,"UTF-8"));
        // 根据文件路径,封装成文件输入流
        InputStream in = new FileInputStream(realPath);
        int len = 0;
        // 声明了一个1kb的字节
        byte[] buffer = new byte[in.available()];
        // byte[] buffer = new byte[in.available()];  //获取文件的总字节大小
        // 获取输出流
        OutputStream out = response.getOutputStream();
        // 循环读取文件,每次读1kb,避免内存溢出
        while((len = in.read(buffer)) != -1){
            // 将缓冲区的数据输出到客户端浏览器
            out.write(buffer,0,len);
        }
        in.close();
        return null;
    }
}

1.2、ResponseEntity 演示

package cool.ale.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author dujlc
 */
@Controller
public class DownLoadController {
    /**
     * ResponseEntity 演示
     * ResponseEntity 可以定制文件的响应内容,响应头,响应状态码
     * @return
     */
    @RequestMapping("/download02")
    public ResponseEntity<String> download02(){
        String body = "Hello World";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Set-Cookie","name=LeLe");
        return new ResponseEntity<String>(body,headers, HttpStatus.OK);
    }
}

1.3、基于spring ResponseEntity 的文件下载

package cool.ale.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author dujlc
 */
@Controller
public class DownLoadController {
    /**
     * 基于spring ResponseEntity 的文件下载 不支持缓冲区
     */
    @RequestMapping("/download03")
    public ResponseEntity<byte[]> download03(HttpServletRequest request) throws IOException {
        // 获取当前项目路径下的下载文件(真是开发中文件名肯定是从数据中读取的)
        String realPath = request.getServletContext().getRealPath("/file/fengjing.jpg");
        // 根据文件路径封装成了File对象
        File tmpFile = new File(realPath);
        // 可以直接根据File对象获取文件名
        String fileName = tmpFile.getName();
        HttpHeaders headers = new HttpHeaders();
        // 设置响应头 content-disposition : 就是设置文件下载的打开方式,默认会在网页上打开
        // 设置 attachment:filename= 就是为了以下下载方式来打开文件
        // "UTF-8"设置如果文件名有中心就不会乱码
        headers.set("Content-Disposition","attachment;filename="
                + URLEncoder.encode(fileName,"UTF-8"));
        // 根据文件路径,封装成文件输入流
        InputStream in = new FileInputStream(realPath);
        return new ResponseEntity<byte[]>(new byte[in.available()],headers,HttpStatus.OK);
    }
}

2、文件上传

2.1、单文件上传

SpringMvc为文件上传提供了直接的支持,这种支持是通过即插即用的MultiPartResolveer实现的。Spring实现了一个MultiPartResolveer实现类:
1、在POM文件中引入commons-fileuploadjar包。
2、在Spring的配置文件中配置CommonsMultipartResolver类并指定文件的最大内存。
3、在控制器处理方法,上传的路径什么的。
代码示例如下:

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<!-- 基于文件上传的解析器 -->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
    <property name="defaultEncoding" value="UTF-8"></property>
    <!-- 最大字节数 -->
    <property name="maxUploadSize" value="#{1024*1024*10}"></property>
</bean>
@Controller
public class UpLoadController {
    /**
     * springMvc 的文件上传
     */
    @RequestMapping("/upload")
    public String upload(String desc, MultipartFile myFile) throws IOException {
        System.out.println(desc);
        System.out.println(myFile.getOriginalFilename());
        String path = "C:\\Users\\dujlc\\Desktop\\fileTest\\" + myFile.getOriginalFilename();
        File file =  new File(path);
        myFile.transferTo(file);
        return "success";
    }
}

2.2、多文件上传–多线程

代码示例:
multiple = “multiple” 可以简写为 multiple,表示可上传多个文件。
accept=“image/*” 在前端可控制上传文件的类型

<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload01" method="post">
    <p>文件描述:<input type="text" name="desc"/></p>
    <p>文件:<input type="file" name="myFile" multiple accept="image/*"/></p>
    <p><input type="submit" value="提交"/></p>
</form>
@RequestMapping("/upload01")
public String upload01(String desc, MultipartFile[] myFile) throws IOException, InterruptedException {
    System.out.println(desc);
    for(final MultipartFile file : myFile){
        Thread thread = new Thread(new Runnable() {
            public void run() {
                System.out.println(file.getOriginalFilename());
                String path = "C:\\Users\\dujlc\\Desktop\\fileTest\\" + file.getOriginalFilename();
                File newFile =  new File(path);
                try {
                    file.transferTo(newFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        thread.join();      // 让子线程执行完成之后再执行主线程
    }

    return "success";
}

3、文件展示

3.1、设置虚拟目录

在Tomcat设置里的Deployment,右键 + 号,即可创建一个虚拟目录,Application context就是那个虚拟路径,可以直接用来访问。

在这里插入图片描述

/**
 * 虚拟目录展示文件
 */
@RequestMapping("/upload02")
public String upload02(String desc, MultipartFile myFile, Model model) throws IOException {
    System.out.println(desc);
    System.out.println(myFile.getOriginalFilename());
    String path = "C:\\Users\\dujlc\\Desktop\\fileTest\\" + myFile.getOriginalFilename();
    File file =  new File(path);
    myFile.transferTo(file);
    model.addAttribute("fileName",myFile.getOriginalFilename());
    return "success";
}
<img src="${pageContext.request.contextPath}/fileTest/${fileName}">
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值