美文网首页
上传下载文件

上传下载文件

作者: 碧波之心 | 来源:发表于2017-12-13 09:16 被阅读23次

下载文件

spring resttemplate下载文件

String suffix = url.substring(url.lastIndexOf("."));
if(CheckUtils.isEmpty(filename)) {
    filename = url.substring(url.lastIndexOf("/") + 1);
} else if(!CheckUtils.isEmpty(suffix)) {
    filename = filename.substring(0, filename.lastIndexOf("."));
    filename += suffix;
}
OutputStream outputStream = null;
byte[] result = restTemplate.getForObject(url, byte[].class);
File file = new File(downloadLocation, filename);
if (!file.getParentFile().exists()) {
    file.getParentFile().mkdirs();
}
if (!file.exists()) {
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
try {
    outputStream = new FileOutputStream(file);
    outputStream.write(result);
    outputStream.flush();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (outputStream != null) {
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

相关文章

网友评论

      本文标题:上传下载文件

      本文链接:https://www.haomeiwen.com/subject/litaixtx.html