After the user uploads the file, the form data is not uploaded, resulting in the accumulation of invalid images

Solution:
Create a temporary folder temp first, store it in the temporary folder when the user uploads the file, and then return this url to the front end,

  1. If the user uploads the form data, then the form data and the url are sent to the backend together, and the backend receives it, and judges whether the url contains /temp/, if it contains it, moves the file to the upload directory, and then modifies the url and saves it in the database; if it does not contain , then upload and update the database normally
  2. If the user does not upload the form data, the file only exists in the temp directory, and we only need to clear the temp directory periodically

Part of the implementation code:

// 判断文件是否存在
const exists = async category_pic => await fs.promises.access(category_pic).then(() => true).catch(_ => false)

// 获取文件名
let fileName = path.basename(category_pic)
// 原文件绝对路径
let filePath = path.join(__dirname, '../uploads/temp/' + fileName)
// 目标文件绝对路径
let newFilePath = path.join(__dirname, '../uploads/categoryPic/' + fileName)
// 存入数据库的url
category_pic = config.fileServer + '/categoryPic/' + fileName

// 移动文件到上传目录
fs.rename(filePath, newFilePath, function(err){
    
    
  if(err) return res.cc(err)
})

Guess you like

Origin blog.csdn.net/cocogogogo/article/details/124360240