简体   繁体   English

为服务器上的文件生成下载链接

[英]Generate a download link for a file on the server

So I built a code that generates a zip file on my server and then deletes it every time a user requests to download the file on the client.所以我构建了一个代码,在我的服务器上生成一个 zip 文件,然后每次用户请求在客户端下载该文件时将其删除。 There is just one more step that I am missing and I can't seem to be able to find a proper solution.我还缺少一个步骤,我似乎无法找到合适的解决方案。 Is there any way I could generate a temporary random link that the server would return to the client that would be a download link for this zip file?有什么方法可以生成一个临时随机链接,服务器将返回给客户端,该链接将成为此 zip 文件的下载链接?

    public String getDownloadLink(String[] files) throws IOException {
        
        [...] // Some stuff goes here but it is irrelevant to the situation. (I generate a download folder!)

        ZipUtil.pack(new File("Download"), new File("selected-files.zip"));

        // Generating a download link
        String downloadLink = ""; // This is what I am trying to figure out!!!


        // Deleting both the folder and the zip
        FileUtils.deleteDirectory(new File("Download"));
        File myObj = new File("selected-files.zip");
        if(myObj.delete()){} else{}

        // Download link
        return downloadLink;
}

A rather simple solution to this problem would be a random file name;这个问题的一个相当简单的解决方案是随机文件名; one that a malicious client cannot guess, so only the initial client can have it.一个恶意客户端无法猜到的,因此只有初始客户端可以拥有它。

A UUID can be used for this purpose as: UUID可用于此目的:

    //...
    String zipFileName = UUID.randomUUID().toString() + ".zip";
    ZipUtil.pack(new File("Download"), new File(zipFileName));
    //...
    String downloadLink = "https://my.server/download?fileName=" + zipFileName;
    //...

Then, when the client actually downloads the file, the request handler will have the fileName query parameter and use it to serve the file (and then perhaps delete it).然后,当客户端实际下载文件时,请求处理程序将具有 fileName 查询参数并使用它来提供文件(然后可能会删除它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM