URL url = new URL(serverUrl + downloadConvertUrl + objectId);
URLConnection conn = url.openConnection();
// 设置超时时间,防止下载卡住
conn.setConnectTimeout(5000); // 设置连接超时时间为 5 秒
conn.setReadTimeout(10000); // 设置读取超时时间为 10 秒
// 设置通用的请求属性
conn.setRequestProperty("Token", getToken());
InputStream inStream = conn.getInputStream();
IOUtils.copy(inStream, new FileOutputStream(file));

下载接口需要的参数

response.setContentType("application/octet-stream");
File file = new File(uploadBasePath + path);
try {
   response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

} catch (UnsupportedEncodingException e) {
   log.error("文件编码异常 : {}", e.getMessage());
}
long downloadSize = file.length();
response.setHeader("Content-Length", downloadSize + "");

IOUtils工具的依赖

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
最后修改:2023 年 11 月 30 日
如果觉得我的文章对你有用,请随意赞赏