Spring MVC 之 文件下载与批量打包下载

  文件下载大多使用输出流的方式来实现。而SpringMVC 提供了一个ResponseEntity类型,可以很方便地定义返回的HttpHeadersHttpStatus

ResponseEntity<byte []>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping("/download")
public class DownLoadFile {

@RequestMapping("/mediafile")
public ResponseEntity<byte []> downloadFile(HttpServletRequest request, HttpServletResponse response,
String fileName,Model model) throws IOException{

//获取文件路径
String filePath = request.getServletContext().getRealPath("/static/img/");
//解决文件名中文乱码问题
String downLoadFileName = new String(fileName.getBytes("utf-8"), "ISO8859-1");
//创建文件对象:路径/文件名,注文件名包含后缀
File file = new File(filePath + File.separator + fileName);

//设置头消息
HttpHeaders headers = new HttpHeaders();
//以附件形式下载
headers.setContentDispositionFormData("attachment", downLoadFileName);
//APPLICATION_OCTET_STREAM:二进制流数据
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte []>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);

return responseEntity;
}
}

输出流方式

使用输出流的方式实现文件下载。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

@Controller
@RequestMapping("/admin/download")
public class DownloadController {

/**
* Android app下载
* 接收下载路径传递 的文件名
* @param request
* @param response
* @param filename
* @param contentType
* @throws Exception
*/
@RequestMapping("/androidapp")
public void downloadApp(HttpServletRequest request, HttpServletResponse response,String filename,String contentType) throws Exception {

//编码转换
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");

BufferedInputStream bis = null;
BufferedOutputStream bos = null;

// String filename = "app-debug.apk";

//文件下载全路径
String filePath = request.getServletContext().getRealPath("/updown/app") + File.separator + filename;

long fileLength = new File(filePath).length();

response.setContentType(contentType);
//处理中文乱码,以附件方式下载
response.setHeader("Content-disposition", "attachment; filename="+ new String(filename.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));

bis = new BufferedInputStream(new FileInputStream(filePath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}
}

批量打包下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import com.xxx.xxx.xxx.FilesMapper;
import com.xxx.xxx.xxx..mapper.OrderMapper;
import com.xxx.xxx.xxx..model.Files;
import com.xxx.xxx.xxx..model.Order;
import com.xxx.xxx.xxx..service.DownloadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
* @Name: DownloadServiceImpl
* @Desc: 下载接口实现
**/
@Service
public class DownloadServiceImpl implements DownloadService {

@Autowired
private FilesMapper filesMapper;
@Autowired
private OrderMapper orderMapper;

@Override
public void batchDownloadOrderFile(HttpServletResponse response, Long orderId) throws IOException {

try {
//获取订单附件
List<Files> filesList = filesMapper.getByOrderId(orderId);
if (filesList != null && filesList.size() != 0) {
Order order = orderMapper.getById(orderId);
//文件名
String batchDonwloadFileName = order.getOrderNo() + ".zip";
//指明response的返回对象是文件流
response.setContentType("application/octet-stream");
//设置在下载框默认显示的文件名
response.setHeader("Content-Disposition", "attachment;filename=" + batchDonwloadFileName);
//打包输出流
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

for (Files file : filesList) {
String downloadUrl = file.getDownloadUrl();
URL url = new URL(downloadUrl);
int i = downloadUrl.lastIndexOf("/");
String fileName = downloadUrl.substring(i + 1, downloadUrl.length());
zos.putNextEntry(new ZipEntry(fileName));
InputStream inputStream = url.openConnection().getInputStream();
byte[] buffer = new byte[1024];
int length = 0;
while (-1 != (length = inputStream.read(buffer, 0, buffer.length))) {
zos.write(buffer, 0, length);
}
inputStream.close();
}
zos.flush();
zos.close();
}
} catch (IOException e) {
throw e;
}
}
}

Spring MVC 之 文件下载与批量打包下载

http://blog.gxitsky.com/2018/02/28/SpringMVC-06-downloadFile/

作者

光星

发布于

2018-02-28

更新于

2022-06-17

许可协议

评论