|
|
|
@ -153,7 +153,53 @@ public class SysOssServiceImpl extends ServiceImpl<SysOssDao, SysOssEntity> impl |
|
|
|
} |
|
|
|
|
|
|
|
@Override |
|
|
|
public void previewOssFileById(Integer id, HttpServletResponse response) throws Exception { |
|
|
|
public void previewOssFileById(Integer id, HttpServletResponse response) { |
|
|
|
SysOssEntity oss = this.getById(id); |
|
|
|
if (Objects.isNull(oss)) { |
|
|
|
throw new IllegalArgumentException("文件不存在"); |
|
|
|
} |
|
|
|
|
|
|
|
// 创建文件对象 |
|
|
|
File file = new File(oss.getUrl()); |
|
|
|
if (!file.exists()) { |
|
|
|
throw new IllegalArgumentException("文件不存在"); |
|
|
|
} |
|
|
|
|
|
|
|
String encodedFileName; |
|
|
|
try { |
|
|
|
encodedFileName = URLEncoder.encode(oss.getFileName(), "UTF-8"); |
|
|
|
} catch (UnsupportedEncodingException e) { |
|
|
|
throw new RuntimeException("文件名编码失败", e); |
|
|
|
} |
|
|
|
|
|
|
|
// 设置响应头 |
|
|
|
if ("txt".equals(oss.getFileSuffix())){ |
|
|
|
response.setContentType("text/plain;charset=utf-8"); |
|
|
|
}else { |
|
|
|
response.setContentType("application/octet-stream;charset=utf-8"); |
|
|
|
} |
|
|
|
response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName); |
|
|
|
|
|
|
|
try (FileInputStream fis = new FileInputStream(file); |
|
|
|
BufferedInputStream bis = new BufferedInputStream(fis); |
|
|
|
ServletOutputStream os = response.getOutputStream()) { |
|
|
|
|
|
|
|
byte[] buffer = new byte[1024]; |
|
|
|
int bytesRead; |
|
|
|
|
|
|
|
// 循环读取文件内容并写入到响应流中 |
|
|
|
while ((bytesRead = bis.read(buffer)) != -1) { |
|
|
|
os.write(buffer, 0, bytesRead); |
|
|
|
} |
|
|
|
|
|
|
|
} catch (IOException e) { |
|
|
|
throw new RuntimeException("文件下载失败", e); |
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
@Override |
|
|
|
public void previewOssFileById2(Integer id, HttpServletResponse response) throws Exception { |
|
|
|
SysOssEntity oss = this.getById(id); |
|
|
|
if (Objects.isNull(oss)) { |
|
|
|
throw new IllegalArgumentException("文件不存在"); |
|
|
|
|