//自己记录将文件保存到本地,主要是记录使用file.getParentFile()方法
private void generateLocalFile(String filePath, byte[] byteArray) {
if (StringUtils.isNotBlank(filePath) && null != byteArray) {
try {
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath);
out.write(byteArray);
out.flush();
out.close();
} catch (Exception e) {
LOGGER.error("本地存储文件失败", e);
}
}
}
//分割线-----------------------------------
//以下为取得文件流后直接返回给前端
public void download(String attId) {
try {
// path是指欲下载的文件的路径。
String fileName = "小狗";
String path = "D:\\dog.png";
File file = new File(path);
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 设置response的Header
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName,"utf-8"));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = response.getOutputStream();
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}