本文为大家分享了Spring4的下载组件,供大家参考,具体内容如下
package com.hnust.common.controller;
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.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@RestController
public class DownloadController extends baseController {
public ResponseEntity export(File file) {
return export(file.getName(), file);
}
public ResponseEntity export(String fileName, File file) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", encodeFileName(fileName));
ResponseEntity rs = null;
try {
// 这里不能使用 HttpStatus.CREATED 201 是因为 IE Edge 无法识别,但是Firefox chrome 没问题
rs = new ResponseEntity<>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.OK);
} catch (IOException e) {
//throw new CommonException(ResponseStatusEnum.FILE_ERROR, e);
}
return rs;
}
private String encodeFileName(String fileName) {
String name = fileName;
try {
String agent = request.getHeader("USER-AGENT").toLowerCase();
if (null != agent && (agent.contains("msie") || agent.contains("edge"))) { // IE edge
name = URLEncoder.encode(fileName, "UTF-8");
} else if (agent.contains("safari") || agent.contains("chrome") || agent.contains("firefox")) { // safari chrome firefox
name = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
} else { // IE10 IE11
name = URLEncoder.encode(fileName, "UTF-8");
}
// 把加号还原为空格(IE Edge 有问题)
name = name.replace("+", "%20");
} catch (UnsupportedEncodingException e) {
//throw new CommonException(ResponseStatusEnum.FAILURE, e);
}
return name;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



