如何将图片从前端上传到后端

Posted

技术标签:

【中文标题】如何将图片从前端上传到后端【英文标题】:how to upload image from frontend to backend 【发布时间】:2017-06-29 16:57:14 【问题描述】:

我有一个名为上传图片的按钮。点击该按钮后,一个模式正在打开。有两个不同的字段,称为图像标题、输入文件。提交保存按钮。它将转到 image.js 文件。我无法理解如何将这些图像保存到我的数据库中。有人请帮助我。

前端代码

/modal.html

         <div class="container">
              <div class="row">
                  <div class="col-md-12">
                      <div class="uploadPhotoGallery">
                          <button type="button" data-toggle="modal" data-target="#myModal" id="uploadButton">Upload Image</button>
                      </div>                     
                  </div>
              </div>
         </div>
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Please Upload Image</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <input type="text" class="form-control" id="imagetitle" placeholder="Image Title">
                </div>
                 <div class="form-group">
                     <input type="file" class="form-control" id="input-image" name="input-image" accept="image/*">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancle</button>
                <button type="submit" class="btn btn-default" id="myFormSubmit">Save</button>
            </div>
        </div>
    </div>
</div>
 <script src="javascript/image.js"></script> 

/image.js

$(function() 
    $('#myFormSubmit').click(function (e) 
       //How to send Image from here to backend
   );
);

Node.js 后端代码

/request.js

exports.addads = function(req, res) 
var addads = req.app.db.model('Adds');
      var data =  imageTitle       : req.body.imageTitle,
                   img              : "http://localhost:4040/"+req.body.img, ;
      var query = addads(data);
      query.save(function(err,data)  
        if(err) 
          console.log(err.toString());
         else   
          //  console.log('Adds Added Successfully');
            res.json( success: true );
            update_routers(req);
          
      );
;

 //Image Logic  
    var file_url = '';
    var storage = multer.diskStorage( //multers disk storage settings
        //console.log("sdfas");
        destination: function (req, file, cb) 
            cb(null, 'public/img/');
        ,
        filename: function (req, file, cb) 
            var datetimestamp = Date.now();
            file_url = file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]
            cb(null, file_url);
        
    );

    var upload = multer( //multer settings
                    storage: storage
                ).single('file');

    /** API path that will upload the files */
    app.post('/uploadImage', function(req, res) 
      //  console.log("req*****", req.fields);
        upload(req,res,function(err)
            if(err)
                 res.json(error_code:1,err_desc:err);
                 return;
            
            console.log("file_url", file_url);
            exec('convert '+ "public/img/" + file_url + " -resize 100x100 " + "public/img/" + file_url, function (err, out) 
              if (err) 
                console.log("error", err);
               else 
                console.log("success");
                res.json(error_code:0,err_desc:null, file_url: 'img/'+file_url);
              
           );
        );
    );

/route.js

router.post('/api/adds', requests.addads);

/schema/ads.js

exports = module.exports = function(app, mongoose) 
     var addsSchema = new mongoose.Schema(
       imageTitle     :  type: String, default: '' ,    
       img            :  type: String, default: '' 

    );
    app.db.model('Adds', addsSchema);
  ;

【问题讨论】:

【参考方案1】:

你需要在你的 nodeJS 后端使用 multer。

前端:

$('#myFormSubmit').click(function (e) 
    var formdata = new FormData()
    formdata.append('photo',$('#input-image').files[0])
    $.ajax(
        method : 'POST',
        processData : false,
        contentType : false,
        url : '/imageupload',
        data : formdata,
        success : function(o)
            //callback here on success
        ,
        error : function(e)
            //callback here on error
        
    )
);

后端(假设应用正在监听):

var multer = require('multer')
var upload = multer(dest : 'uploads/').single('photo') 
//make sure you have access to write files
//make sure 'photo' matches up with the field entered at the front end e.g. formdata.append('photo', ...)

app.post('/imageupload',upload,function(req,res)
    //req.file will now be available as a json object, save to mongodb, re: filename, path etc
    res.send('rabbit')
)

【讨论】:

以上是关于如何将图片从前端上传到后端的主要内容,如果未能解决你的问题,请参考以下文章

如何将图像从前端(reactjs)传递到后端(nodejs)并将其上传到firebase存储?

前端上传图片变成var

ant design pro上传图片到后端

前端传入导入文件地址到后端报错

前端压缩并上传图片

SpringBoot+Vue+token实现(表单+图片)上传图片地址保存到数据库。上传图片保存位置自己定义图片可以在前端回显)