图像从android上传到nodejs

时间:2017-01-21 08:15:29

标签: node.js image

如何从Android获取图像?  我用了console.log(request.files.image.originalFilename); 如何在nodejs服务器中读取图像。  的console.log(request.files.image.path); 任何人都可以给出解决方案如何获取文件以及如何读取文件? 我没有定义错误图像。

var express=require("express");
var app=express();
var multer=require("multer");
var path=require("path");
var fs=require("fs");
var bodyparser=require("body-parser");
var urlencoded=bodyparser.urlencoded({extended:false});
app.use(bodyparser.json({limit: "50mb"}));
app.use(bodyparser.urlencoded({limit: "50mb", extended: true,parameterLimit:50000}));
app.post("/uploadimage",urlencoded,function(request,response)
{
    console.log("I got a request");
    console.log(request.files.image.originalFilename);
    fs.readFile(request.files.image.path,function (err, data)
    {
        var dirname = "C:/Users/Kishore Baskar/WebstormProjects/Confident";
        var newPath = dirname + "/imagesfolder/one.jpg";
        fs.writeFile(newPath, data, function (err)
        {
            if (err)
            {
                console.log("file not written");
            }
            else
            {
                console.log("file written successfully");
            }
        });
    });
});

app.listen(8086,function()
{
    console.log("server listen at port 8086");
});

1 个答案:

答案 0 :(得分:0)

        import multer from 'multer';   
// Where you want to store file locally 
        var storage = multer.diskStorage({
           destination: function(req, file, cb) {
               cb(null, './uploads/');
           },
           filename: function(req, file, cb) {
               cb(null, file.originalname)
           }
        })
        try{
          var upload = multer({ 
            storage: storage,
            fileFilter: function (req, file, callback) {
                  var ext = path.extname(file.originalname);
                  if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
                      return callback(new Error('Only images are allowed'))
                  }
                  callback(null, true)
              },
              limits:{
                  fileSize: 1024 * 1024
              }
          });
        } catch(e){
          console.log("Error File in file Upload Filter",e);
        }

        **//storage: storage }).single('file') file is file name object like : file:fileobject from client**
        router.post('/uploadImage',multer({ storage: storage }).single('file'),(req,res,next) => {
          try {
    // Get File Here 
        console.log(req.file);
        } catch(e){
        console.log(e)
        }