我创建了一个可以上传文件的项目,例如 Dropbox,部署到 Heroku 并且工作正常,但现在我想从 Heroku 服务器删除该文件。
我从数据库中删除了具有关系的路径,但是我尝试了很多方法从服务器中删除文件但没有成功,最后一个通过fs.unlink()
,这似乎是最好的使用:
//working example
const file = {url: 'https://mobox-app.herokuapp.com/files/dbd3917046ec3075f2a424e07c9a39aa-1*hoSDm9oecgsKShbAroI2XQ.jpeg'}
async deleteFile(req, res){
const file = await File.findById(req.body.fileId),
fileId = req.body.fileId
await File.deleteOne( {_id: fileId}).then(
fs.unlink(file.url, (err) => {
if (err) {
console.error(err)
return
}
})
)
}
这是heroku日志给我的:
2019-06-28T16:01:43.514606+00:00 app[web.1]: { [Error: ENOENT: no such file or directory, unlink 'https://mobox-app.herokuapp.com/files/dbd3917046ec3075f2a424e07c9a39aa-1*hoSDm9oecgsKShbAroI2XQ.jpeg']
2019-06-28T16:01:43.514645+00:00 app[web.1]: errno: -2,
2019-06-28T16:01:43.514648+00:00 app[web.1]: code: 'ENOENT',
2019-06-28T16:01:43.514650+00:00 app[web.1]: syscall: 'unlink',
2019-06-28T16:01:43.514652+00:00 app[web.1]: path:
2019-06-28T16:01:43.514654+00:00 app[web.1]: 'https://mobox-app.herokuapp.com/files/dbd3917046ec3075f2a424e07c9a39aa-1*hoSDm9oecgsKShbAroI2XQ.jpeg' }
它找不到路径,如果我仅将 '/files/fileName.ext'
或仅将 'fileName.ext'
作为 则相同文件.url
。我怎样才能删除这些文件?
最佳答案
I've created a project that I can upload files, like Dropbox, deployed to Heroku and it works fine, but now I want to delete the file from Heroku server.
您可能需要仔细观察并思考“工作正常”意味着什么。
Heroku 的文件系统 is ephemeral :您所做的任何更改(例如存储文件)都将在下次 dyno 重新启动时丢失。这个happens frequently (每天至少一次)。无论您是否愿意,您上传的内容都会被自动删除。
Heroku recommends将用户上传的内容存储在 Amazon S3 等第三方服务上。您必须迁移到类似的东西才能使存储部分正常工作,并且当您想要删除文件时,您必须使用您选择的服务提供的任何工具。
关于node.js - 从 Heroku 服务器删除上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56810275/