parent
7419289519
commit
df27ca9d83
@ -0,0 +1,50 @@ |
|||||||
|
package com.keyware.shandan.common.util; |
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletResponse; |
||||||
|
import java.io.BufferedInputStream; |
||||||
|
import java.io.File; |
||||||
|
import java.io.IOException; |
||||||
|
import java.io.OutputStream; |
||||||
|
import java.nio.charset.StandardCharsets; |
||||||
|
import java.nio.file.Files; |
||||||
|
|
||||||
|
public class FileDownload { |
||||||
|
public static String download(HttpServletResponse response, File file, boolean deleteFile) { |
||||||
|
return download(response, file, file.getName(), deleteFile); |
||||||
|
} |
||||||
|
|
||||||
|
public static String download(HttpServletResponse response, File file, String fileName) { |
||||||
|
return download(response, file, fileName, false); |
||||||
|
} |
||||||
|
|
||||||
|
public static String download(HttpServletResponse response, File file, String fileName, boolean deleteFile) { |
||||||
|
try (BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(file.toPath())); |
||||||
|
OutputStream out = response.getOutputStream()) { |
||||||
|
response.setCharacterEncoding("UTF-8"); |
||||||
|
response.setContentType("application/octet-stream"); |
||||||
|
byte[] fileNameBytes = fileName.getBytes(StandardCharsets.UTF_8); |
||||||
|
response.setHeader("Content-disposition", "attachment;filename=" + new String(fileNameBytes, 0, fileNameBytes.length, StandardCharsets.ISO_8859_1)); |
||||||
|
|
||||||
|
byte[] buffer = new byte[1024]; // 缓冲区
|
||||||
|
int bytesToRead = 0; |
||||||
|
// 通过循环将读入的Word文件的内容输出到浏览器中
|
||||||
|
while ((bytesToRead = bis.read(buffer)) != -1) { |
||||||
|
out.write(buffer, 0, bytesToRead); |
||||||
|
out.flush(); |
||||||
|
} |
||||||
|
} catch (IOException e) { |
||||||
|
throw new RuntimeException(e); |
||||||
|
} finally { |
||||||
|
if (deleteFile) { |
||||||
|
try { |
||||||
|
Thread.sleep(100); |
||||||
|
} catch (InterruptedException ignored) { |
||||||
|
} |
||||||
|
file.deleteOnExit(); |
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
return "download success"; |
||||||
|
} |
||||||
|
} |
Reference in new issue