将上载的文件存储在Express中系统中除项目公用文件夹之外的任何路径中

时间:2018-07-30 10:42:19

标签: javascript node.js reactjs express

我要从React上传的前端文件上传到Express js中。但是现在,如果我将其存储在Express中,则该文件将存储在公用文件夹中。

如果我要将文件存储在系统中可以是任何路径的非公用文件夹中,那么该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以从react客户端获取图像作为base64字符串,并使用后端中的以下代码对图像字符串进行解码。然后将图片存储在任何文件夹中。尝试这样做可能对您有帮助

  var fs = require('fs');
  var path = require('path');
  var ID = req.body.id;
  var DOC = req.body.doc;   //Base64 Image String

      var dir = './myapp//asset/'+ID;
      if (!fs.existsSync(dir)){
        fs.mkdirSync(dir);
      }

  var base64Data1 = DOC.replace(/^data:image\/jpg;base64,/, "");
    require("fs").writeFile( val= './myapp/asset/'+ID+'/'+ID+'_1'+'.jpg',base64Data1,'base64', function(err) {
   });

   var absolutePath1 = path.resolve(val);
   var abs1 = JSON.stringify(absolutePath1);
   var v1 = abs1.replace(/"/g,"");

如果您使用普通图像,则可以这样做

 var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path'),
   busboy = require("then-busboy"),
   fileUpload = require('express-fileupload'),
   app = express(),
   bodyParser=require("body-parser");

    app.use(express.static(path.join(__dirname, 'asset')));
    app.use(fileUpload());


      function(req, res){
     message = '';
      if(req.method == "POST"){

       if (!req.files)
            return res.status(400).send('No files were uploaded.');

    var file = req.files.uploaded_image;
    var img_name=file.name;

     if(file.mimetype == "image/jpeg" ||file.mimetype == "image/png"||file.mimetype == "image/gif" ){

          file.mv('E:/asset/images/upload_images/'+file.name, function(err) {

              if (err)

                return res.status(500).send(err);
                    var sql = "INSERT INTO `users_image`( `image`) VALUES ('" + img_name + "')";

                        var query = db.query(sql, function(err, result) {
                             res.send('profile');
                        });
                   });
      } else {

        res.render('index.ejs',{message: message});
      }
     } else {
     res.render('index');
    }

 };