下面列出了org.springframework.http.HttpHeaders#setContentDispositionFormData ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static ResponseEntity<Object> export(File file) {
if (!file.exists()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("404 FILE NOT FOUND");
}
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.setContentDispositionFormData("attachment", URLUtil.encode(file.getName()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(mediaType)
.body(new FileSystemResource(file));
}
@RequestMapping(value = "/api/{companyId}/projects/{projectId}/attachments/{attachmentId}/download", method = RequestMethod.GET)
@ResponseBody
public HttpEntity<byte[]> downloadAttachment(@PathVariable("companyId") int companyId,
@PathVariable("projectId") int projectId, @PathVariable("attachmentId") int attachmentId, HttpServletRequest request)
throws IOException {
String byteUri = String.format(ATTACHMENT_BYTE, companyId, projectId, attachmentId);
String attachmentUri = String.format(ATTACHMENT_ID, companyId, projectId, attachmentId);
byte[] bytes = netService.getForObject(byteUri, byte[].class);
AttachmentDTO attachment = netService.getForObject(attachmentUri, AttachmentDTO.class);
if (attachment == null || bytes == null) {
throw new com.onboard.frontend.exception.ResourceNotFoundException();
}
HttpHeaders header = new HttpHeaders();
String filename = new String(attachment.getName().getBytes("GB2312"), "ISO_8859_1");
header.setContentDispositionFormData("attachment", filename);
return new HttpEntity<byte[]>(bytes, header);
}
/**
* 下载
* @param file 文件
* @param fileName 生成的文件名
* @return {ResponseEntity}
*/
protected ResponseEntity<Resource> download(File file, String fileName) {
Resource resource = new FileSystemResource(file);
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
String header = request.getHeader("User-Agent");
// 避免空指针
header = header == null ? "" : header.toUpperCase();
HttpStatus status;
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
fileName = URLUtils.encodeURL(fileName, Charsets.UTF_8);
status = HttpStatus.OK;
} else {
fileName = new String(fileName.getBytes(Charsets.UTF_8), Charsets.ISO_8859_1);
status = HttpStatus.CREATED;
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity<Resource>(resource, headers, status);
}
public ResultEntity uploads(String category, String version, String type, MultipartFile jarFile) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setContentDispositionFormData("jarFile", jarFile.getOriginalFilename());
MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();
File saveDir = new File(SystemUtils.getJavaIoTmpDir(), String.valueOf(System.currentTimeMillis()));
if (!saveDir.exists()) saveDir.mkdirs();
File tempFile = new File(saveDir, jarFile.getOriginalFilename());
jarFile.transferTo(tempFile);
FileSystemResource fsr = new FileSystemResource(tempFile);
data.add("jarFile", fsr);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(data, headers);
URLBuilder urlBulider = new URLBuilder(ServiceNames.KEEPER_SERVICE, "/jars/uploads/{0}/{1}/{2}");
ResponseEntity<ResultEntity> result = rest.postForEntity(urlBulider.build(), entity, ResultEntity.class, version, type, category);
if (tempFile.exists()) tempFile.delete();
if (saveDir.exists()) saveDir.delete();
return result.getBody();
}
public ResultEntity uploadsEncodePlugin(String name, Integer projectId, MultipartFile jarFile) throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setContentDispositionFormData("jarFile", jarFile.getOriginalFilename());
MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();
File saveDir = new File(SystemUtils.getJavaIoTmpDir(), String.valueOf(System.currentTimeMillis()));
if (!saveDir.exists()) saveDir.mkdirs();
File tempFile = new File(saveDir, jarFile.getOriginalFilename());
jarFile.transferTo(tempFile);
FileSystemResource fsr = new FileSystemResource(tempFile);
data.add("jarFile", fsr);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(data, headers);
URLBuilder urlBulider = new URLBuilder(ServiceNames.KEEPER_SERVICE, "/jars/uploads-encode-plugin/{0}/{1}");
ResponseEntity<ResultEntity> result = rest.postForEntity(urlBulider.build(), entity, ResultEntity.class, name, projectId);
if (tempFile.exists()) tempFile.delete();
if (saveDir.exists()) saveDir.delete();
return result.getBody();
}
@Override
public ResponseEntity<byte[]> gainPic(String dir, String picName){
File file=new File(setting.getPicHome()+File.separatorChar+dir+File.separatorChar+picName);
byte[] bytes;
try {
bytes= FileTools.readFileToByteArray(file);
} catch (Exception e) {
log.warn(e.getLocalizedMessage());
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", picName);
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
@GetMapping("/{workflowId:\\d+}/generatePDF.action")
public ResponseEntity<byte[]> generatePDF(ComAdmin admin, @PathVariable int workflowId,
@RequestParam("showStatistics") String showStatistics) throws Exception {
String jsessionid = RequestContextHolder.getRequestAttributes().getSessionId();
String hostUrl = configService.getValue(ConfigValue.SystemUrl);
String url = hostUrl + "/workflow/viewOnlyElements.action;jsessionid=" + jsessionid + "?workflowId=" + workflowId + "&showStatistics=" + showStatistics + "&isWkhtmltopdfUsage=true";
String workflowName = workflowService.getWorkflow(workflowId, admin.getCompanyID()).getShortname();
File pdfFile = generationPDFService.generatePDF(configService.getValue(ConfigValue.WkhtmlToPdfToolPath), url, HttpUtils.escapeFileName(workflowName), admin, "wmLoadFinished", "Landscape", "workflow.single", WORKFLOW_CUSTOM_CSS_STYLE);
ResponseEntity<byte[]> response = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
if (pdfFile != null) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData(workflowName, workflowName + ".pdf");
if (pdfFile.exists()) {
response = new ResponseEntity<>(Files.readAllBytes(pdfFile.toPath()), headers, HttpStatus.OK);
try {
pdfFile.delete();
} catch (Exception e) {
logger.error("Cannot delete temporary pdf file: " + pdfFile.getAbsolutePath(), e);
}
writeUserActivityLog(admin, "export workflow", "WorkflowID: " + workflowId);
}
}
return response;
}
/**
* 返回前台文件流
*
* @author fengshuonan
* @date 2017年2月28日 下午2:53:19
*/
protected ResponseEntity<byte[]> renderFile(String fileName, byte[] fileBytes) {
String dfileName = null;
try {
dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", dfileName);
return new ResponseEntity<byte[]>(fileBytes, headers, HttpStatus.CREATED);
}
@PostMapping("/exportExam")
public ResponseEntity<byte[]> exportExam() throws Exception {
byte[] bytes = examService.exportExam();
HttpHeaders headers = new HttpHeaders();
String fileName = URLEncoder.encode("考试信息", StandardCharsets.UTF_8.name());
headers.setContentDispositionFormData("attachment", fileName + ".xlsx");
headers.setContentType(new MediaType("application", "vnd.ms-excel"));
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
public static ResponseEntity<Object> export(File file, String fileName) {
if (!file.exists()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("404 FILE NOT FOUND");
}
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
if (StringUtils.isNullOrEmpty(fileName)) {
fileName = file.getName();
}
headers.setContentDispositionFormData("attachment", URLUtil.encode(fileName));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(mediaType)
.body(new FileSystemResource(file));
}
@RequestMapping("download")
public ResponseEntity<byte[]> download() throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "README.md");
File file = new File("README.md");
System.out.println(file.getAbsolutePath());
System.out.println(this.getClass().getResource(""));
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
@RequestMapping("/thread")
public ResponseEntity<byte[]> threadDump(String id) throws IOException {
String dump = Jstack.dump(id);
File file = new File(dump);
logger.debug("DownLoad Dump:"+dump);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", file.getName());
return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}
@RequestMapping("/heap")
public ResponseEntity<byte[]> heapDump() throws IOException {
String dump = Jmap.dump();
File file = new File(dump);
logger.debug("DownLoad Dump:"+dump);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", file.getName());
return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}
@RequestMapping("/thread")
public ResponseEntity<byte[]> threadDump() throws IOException {
String dump = Jstack.dump();
File file = new File(dump);
logger.debug("DownLoad Dump:"+dump);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", file.getName());
return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}
private ResponseEntity<byte[]> writeDataToOutputStream(final Operation<E> operation,
final String fileNameWithoutExtension) throws IOException, E {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
operation.accept(outputStream);
final byte[] output = outputStream.toByteArray();
final HttpHeaders headers = new HttpHeaders();
final ExportFormat exportFormat = getExportFormat();
headers.setContentType(MediaType.parseMediaType(exportFormat.getMimeType()));
final String fileName = fileNameWithoutExtension + FilenameUtils.EXTENSION_SEPARATOR + exportFormat.getExtension();
headers.setContentDispositionFormData(fileName, fileName);
return new ResponseEntity<>(output, headers, HttpStatus.OK);
}
@Override
public HttpHeaders getResponseHeaders() {
HttpHeaders headers = new HttpHeaders();
// Modified to show download
Object originalFileName = BeanUtils.getFieldWithAnnotation(entity, OriginalFileName.class);
if (originalFileName != null) {
headers.setContentDispositionFormData("attachment", (String) originalFileName);
}
return headers;
}
@RequestMapping("exportexcel")
public ResponseEntity<byte[]> exportexcel(Store store) throws IOException {
SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String prefix = "store_";
String fileName = prefix + sdfFileName.format(Calendar.getInstance().getTime()) + ".xls";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
File file = new File("export/" + fileName);
OutputStream output = null;
AuthUser currUser = BaseController.getCurrUser();
if (!StringUtils.isEmpty(currUser.getMember().getCompanyCode())) {
if (null == store) {
store = new Store();
}
store.setAgentCode(currUser.getMember().getCompanyCode());
}
List<Store> storeList = this.storeService.getStoreList(store);
Workbook wb = new HSSFWorkbook();
int sheetCount = 0;
Sheet sheet = null;
Row row = null;
Cell cell = null;
Store generateStroe = null;
int minLength = 0;
try {
output = new FileOutputStream(file);
if(null != storeList && !storeList.isEmpty()) {
sheetCount = storeList.size() % CommonConstant.XLS_MAX_LINE == 0 ? storeList.size() / CommonConstant.XLS_MAX_LINE :
(storeList.size() / CommonConstant.XLS_MAX_LINE + 1);
for(int i = 0; i < sheetCount; i++) {
sheet = wb.createSheet(prefix + i);
minLength = storeList.size() >= (i + 1) * CommonConstant.XLS_MAX_LINE ? CommonConstant.XLS_MAX_LINE :
storeList.size() - i * CommonConstant.XLS_MAX_LINE;
row = sheet.createRow(0);
row.createCell(0).setCellValue("账册号");
row.createCell(1).setCellValue("经营单位");
row.createCell(2).setCellValue("料号");
row.createCell(3).setCellValue("HS编码");
row.createCell(4).setCellValue("商品名称");
row.createCell(5).setCellValue("规格");
row.createCell(6).setCellValue("成交单价");
row.createCell(7).setCellValue("成交币制");
row.createCell(8).setCellValue("单位");
row.createCell(9).setCellValue("出库");
row.createCell(10).setCellValue("入库");
row.createCell(11).setCellValue("库存");
for(int j = 0; j < minLength; j++) {
generateStroe = storeList.get(i * CommonConstant.XLS_MAX_LINE + j);
row = sheet.createRow(j + 1);
row.createCell(0).setCellValue(generateStroe.getLmsNo());
row.createCell(1).setCellValue(generateStroe.getTradeName());
row.createCell(2).setCellValue(generateStroe.getItemNo());
row.createCell(3).setCellValue(generateStroe.getCodeTs());
row.createCell(4).setCellValue(generateStroe.getgName());
row.createCell(5).setCellValue(generateStroe.getgModel());
row.createCell(6).setCellValue(generateStroe.getDeclPrice());
row.createCell(7).setCellValue(ParaTool.getCurrDesc(generateStroe.getTradeCurr(), this.currService)
+ "[" + generateStroe.getTradeCurr() + "]");
row.createCell(8).setCellValue(ParaTool.getUnitDesc(generateStroe.getUnit(), this.unitService)
+ "[" + generateStroe.getUnit() + "]");
row.createCell(9).setCellValue(generateStroe.getLegalOQty());
row.createCell(10).setCellValue(generateStroe.getLegalIQty());
row.createCell(11).setCellValue(generateStroe.getLegalRemainQty());
}
}
}
wb.write(output);
output.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
output.close();
}
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
@SuppressWarnings("unchecked")
private <T> Flux<DataBuffer> encodePart(byte[] boundary, String name, T value) {
MultipartHttpOutputMessage outputMessage = new MultipartHttpOutputMessage(this.bufferFactory, getCharset());
HttpHeaders outputHeaders = outputMessage.getHeaders();
T body;
ResolvableType resolvableType = null;
if (value instanceof HttpEntity) {
HttpEntity<T> httpEntity = (HttpEntity<T>) value;
outputHeaders.putAll(httpEntity.getHeaders());
body = httpEntity.getBody();
Assert.state(body != null, "MultipartHttpMessageWriter only supports HttpEntity with body");
if (httpEntity instanceof MultipartBodyBuilder.PublisherEntity<?, ?>) {
MultipartBodyBuilder.PublisherEntity<?, ?> publisherEntity =
(MultipartBodyBuilder.PublisherEntity<?, ?>) httpEntity;
resolvableType = publisherEntity.getResolvableType();
}
}
else {
body = value;
}
if (resolvableType == null) {
resolvableType = ResolvableType.forClass(body.getClass());
}
if (!outputHeaders.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
if (body instanceof Resource) {
outputHeaders.setContentDispositionFormData(name, ((Resource) body).getFilename());
}
else if (resolvableType.resolve() == Resource.class) {
body = (T) Mono.from((Publisher<?>) body).doOnNext(o -> outputHeaders
.setContentDispositionFormData(name, ((Resource) o).getFilename()));
}
else {
outputHeaders.setContentDispositionFormData(name, null);
}
}
MediaType contentType = outputHeaders.getContentType();
final ResolvableType finalBodyType = resolvableType;
Optional<HttpMessageWriter<?>> writer = this.partWriters.stream()
.filter(partWriter -> partWriter.canWrite(finalBodyType, contentType))
.findFirst();
if (!writer.isPresent()) {
return Flux.error(new CodecException("No suitable writer found for part: " + name));
}
Publisher<T> bodyPublisher =
body instanceof Publisher ? (Publisher<T>) body : Mono.just(body);
// The writer will call MultipartHttpOutputMessage#write which doesn't actually write
// but only stores the body Flux and returns Mono.empty().
Mono<Void> partContentReady = ((HttpMessageWriter<T>) writer.get())
.write(bodyPublisher, resolvableType, contentType, outputMessage, DEFAULT_HINTS);
// After partContentReady, we can access the part content from MultipartHttpOutputMessage
// and use it for writing to the actual request body
Flux<DataBuffer> partContent = partContentReady.thenMany(Flux.defer(outputMessage::getBody));
return Flux.concat(Mono.just(generateBoundaryLine(boundary)), partContent, Mono.just(generateNewLine()));
}
@RequestMapping("export")
public ResponseEntity<byte[]> export(Store store) throws IOException {
SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fileName = "store_" + sdfFileName.format(Calendar.getInstance().getTime()) + ".csv";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
File file = new File("export/" + fileName);
PrintWriter writer = null;
OutputStream output = null;
AuthUser currUser = BaseController.getCurrUser();
if (!StringUtils.isEmpty(currUser.getMember().getCompanyCode())) {
if (null == store) {
store = new Store();
}
store.setAgentCode(currUser.getMember().getCompanyCode());
}
List<Store> storeList = this.storeService.getStoreList(store);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
output = new FileOutputStream(file);
output.write(CommonConstant.BOM);
output.close();
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8")));
writer.println("账册号,经营单位,料号,HS编码,商品名称,规格,成交单价,成交币制,单位,出库,入库,库存");
for(Store s : storeList) {
writer.print(s.getLmsNo());
writer.print("," + s.getTradeName());
writer.print("," + s.getItemNo());
writer.print("," + s.getCodeTs());
writer.print("," + s.getgName());
writer.print("," + s.getgModel());
writer.print("," + s.getgModel());
writer.print("," + s.getDeclPrice());
writer.print("," + ParaTool.getCurrDesc(s.getTradeCurr(), this.currService));
writer.print("," + ParaTool.getUnitDesc(s.getUnit(), this.unitService));
writer.print("," + s.getLegalOQty());
writer.print("," + s.getLegalIQty());
writer.print("," + s.getLegalRemainQty());
writer.println();
}
writer.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
output.close();
writer.close();
}
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
/**
* 文件下载辅助
*
* @param filePath
* 文件路径
* @param fileName
* 文件名
* @return
* @throws UnsupportedEncodingException
* @throws IOException
*/
private static ResponseEntity<byte[]> downloadAssist(String filePath, String fileName) throws UnsupportedEncodingException, IOException {
File file = new File(filePath);
if (!file.isFile() || !file.exists()) {
throw new IllegalArgumentException("filePath 参数必须是真实存在的文件路径:" + filePath);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, ENCODING));
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}