求java通过get请求下载文件到本地存放的代码
比如从下面这个链接下载到pdf文件
https://bswj.fpggfwpt.guangxi.chinatax.gov.cn:19001/api?action=getDoc&code=045002100111_596880_2022015_A6F4A0H2&type=12
在网路上找了好多代码,都无法使用
您好,一般针对这种需求,可以有以下的实现方式:
1、针对这种pdf类的文件,可以直接通过http服务把文件放出来,可以直接进行文件的预览,一般的比如chrome浏览器会自带了下载功能。
2、自己手写代码的方式,可以参考以下的代码:
@GetMapping("/download")
public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request){
try {
if (!FileUtils.checkAllowDownload(fileName)){
throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
}
String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
String filePath = HngtghyConfig.getDownloadPath() + fileName;
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, realFileName);
FileUtils.writeBytes(filePath, response.getOutputStream());
if (delete){
FileUtils.deleteFile(filePath);
}
}catch (Exception e) {
log.error("下载文件失败", e);
}
}
/**
* 输出指定文件的byte数组
*
* @param filePath 文件路径
* @param os 输出流
* @return
*/
public static void writeBytes(String filePath, OutputStream os) throws IOException
{
FileInputStream fis = null;
try
{
File file = new File(filePath);
if (!file.exists())
{
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0)
{
os.write(b, 0, length);
}
}
catch (IOException e)
{
throw e;
}
finally
{
IOUtils.close(os);
IOUtils.close(fis);
}
}