简体   繁体   English

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

[英]how to upload image from frontend to backend

I have a button called Upload Image .On click that button,a modal is opening.我有一个名为Upload Image的按钮。单击该按钮后,将打开一个模式。 There is two different field called Image Title, Input File .有两个不同的字段,称为Image Title 和 Input File On submit the Save button.提交保存按钮。 It will go to the image.js file.它将转到image.js文件。 I am not able to understand how to save these image to my database.我无法理解如何将这些图像保存到我的数据库中。 someone please help me.有人请帮助我。

Frontend Code前端代码

/modal.html /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 /image.js

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

Node.js Backend Code Node.js 后端代码

/request.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 /route.js

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

/schema/ads.js /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);
  };

You will need multer on your nodeJS backend.您将需要在您的 nodeJS 后端使用 multer。

Front end:前端:

$('#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
        }
    })
});

back end (assuming app is listening):后端(假设应用程序正在监听):

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')
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何安全地从后端发送图像以显示在前端 HTML? - How to securely send image from backend to be displayed in frontend HTML? 如何使用 ActiveStorage 上传图片到后端并获取发送到前端的响应中包含的图片的 url - how to use ActiveStorage to upload image to the backend and get the url for the image inclded in the response sent to the frontend 从js前端上传json文件到zhttp后端 - Upload json file from js frontend to zhttp backend 如何在React中将数据从后端推送到前端 - How to push data from backend to frontend in react 如何从后端到前端使用 Axios - How to use Axios from backend to frontend 如何从前端的后端下载excel文件? - How to dowload an excel file from backend in frontend? 如何从前端脚本调用后端代码 - How to call backend code from frontend script 如何从快速后端服务器获取图像并将其显示到 React Native 前端? - How to Fetch and Display an Image from an express backend server to a React Native frontend? 如何从快速后端服务器获取图像并将其显示到 React js 前端? - How to Fetch and Display an Image from an express backend server to a React js frontend? 通常无法将图像从前端发送到云端或后端 - Unable to send image from frontend to cloudinary or the backend in general
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM