cloudwego / hertz

Go HTTP framework with high-performance and strong-extensibility for building micro-services.
https://www.cloudwego.io
Apache License 2.0
5.04k stars 491 forks source link

how to delete file promptly after ctx.FileAttachment(file) #1113

Open anyfig opened 3 months ago

anyfig commented 3 months ago

Describe the Question hello, friends, delete a file after download it is a very common requirement in business, i want to impl it in hertz, and meet this problem, err: The process cannot access the file because it is being used by another process. Reproducible Code in java, its ok to delete file after download it.

public void fileDownload(String fileName, Boolean delete, HttpServletResponse response){
    FileUtils.writeBytes(baseDir+fileName, response.getOutputStream());
    if (delete){
        FileUtils.deleteFile(baseDir+fileName);
    }
}

in hertz, I tried two ways, neither work. (err: The process cannot access the file because it is being used by another process)

func FileDownload1(ctx context.Context, c *app.RequestContext) {
    if req.Delete {
        go func() {
            time.Sleep(15 * time.Second)
            DeleteFile(baseDir+req.FileName)
        }()
    }
    c.FileAttachment(baseDir+req.FileName, req.FileName)
}
func FileDownload2(ctx context.Context, c *app.RequestContext) {
    if req.Delete {
        defer DeleteFile(baseDir+req.FileName)
    }
    c.FileAttachment(baseDir+req.FileName, req.FileName)
}

Additional context in FileDownload1, when time.Sleep(enough_time), file would be deleted successfully, but the time is uncontrollable.

li-jin-gou commented 3 months ago

c.FileAttachment(baseDir+req.FileName, req.FileName) DeleteFile(baseDir+req.FileName)

anyfig commented 3 months ago

c.FileAttachment(baseDir+req.FileName, req.FileName) DeleteFile(baseDir+req.FileName)

不行啊 c.FileAttachment()后跟DeleteFile()或defer DeleteFile()都一样 222

li-jin-gou commented 3 months ago

看了一下代码,因为文件正在传输,hertz在读取文件,所以立刻删除失败了,需要等请求结束才能删除成功。

anyfig commented 3 months ago

看了一下代码,因为文件正在传输,hertz在读取文件,所以立刻删除失败了,需要等请求结束才能删除成功。

c.FileAttachment()函数的文件传输好像是在另一个goroutine中,什么时候完成下载还没办法判断。o(╥﹏╥)o,有没有其他办法

li-jin-gou commented 3 months ago

看了一下代码,因为文件正在传输,hertz在读取文件,所以立刻删除失败了,需要等请求结束才能删除成功。

c.FileAttachment()函数的文件传输好像是在另一个goroutine中,什么时候完成下载还没办法判断。o(╥﹏╥)o,有没有其他办法

一起研究下看看,可以飞书群联系下我