当前位置 : 主页 > 网络编程 > JavaScript >

NodeJS上传文件

来源:互联网 收集:自由互联 发布时间:2021-06-28
gistfile1.txt var fileUpload=(files)={ //如果files文件夹不存在 if (!fs.existsSync(path.resolve(__dirname,"..") + "/public/images/goods/")) { //动态创建files文件夹 fs.mkdir(path.resolve(__dirname,"..")+ "/public/images/goods/"
gistfile1.txt
var fileUpload=(files)=>{
  //如果files文件夹不存在
  if (!fs.existsSync(path.resolve(__dirname,"..") + "/public/images/goods/")) {
      //动态创建files文件夹
      fs.mkdir(path.resolve(__dirname,"..")+ "/public/images/goods/", function (err) {
          if (err) {
              console.log("创建文件夹失败" + err);
          }
      })
  }
  console.log("文件个数:"+files.length);
  for (var f of files) {
    var des_file = path.resolve(__dirname,"..")+ "/public/images/goods/" + f.originalname; //上传的目标路径
    console.log("上传路径:"+des_file);//上传路径
    var data = fs.readFileSync(f.path); //读取文件的原始路径
    fs.writeFile(des_file, data, function (err) {
        err && console.log(err);
    })
  }
  return "./images/goods/" + files[0].originalname;
}
网友评论