Ionic 2/3:使用Node JS

时间:2018-05-14 11:09:38

标签: node.js ionic3

我正在尝试从Gallery / Camera上传图片。我的后端是Nodejs。我能够上传一个文件,但它似乎不是一个jpeg.It看起来像一个没有任何扩展名的编码文件,我得到这个错误:

  

{ “代码”:3, “源极”: “文件:///storage/emulated/0/Android/data/io.ionic.starter/cache/1526315072575.jpg”, “目标”:“{{ 3}}“,”http_status“:null,”body“:null,”exception“:”com.android.okhttp.Address@cff2e20a上的意外流结束“}

这是Node Js:

var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
var server = require('http').Server(app);
var mongoose = require('mongoose');                 // mongoose for mongodb
var port = process.env.PORT || 8000;                // set the port
var database = require('./config/database');            // load the database config
var morgan = require('morgan');
var methodOverride = require('method-override');
var io = require('socket.io')(server);
var cors = require('cors');
var multer = require('multer');
var messageId = {};
var fs = require('fs');
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(cors());
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  next();
});

 app.use(bodyParser.urlencoded({ extended: false }));
 app.use(bodyParser.json());

var upload = multer({dest :'user-img/'});

var uploadTradeRouter = express.Router();

uploadTradeRouter.post('/trade' , upload.any() , function(req, res, next){
         console.log('trade data called' +req);
});
app.use('/upload' , uploadTradeRouter);
app.listen(port);

这是我的uploadimage.ts

import { Component, ViewChild  } from '@angular/core';
import { NavController, Navbar, NavParams ,Platform,AlertController,ToastController, LoadingController, ActionSheetController, ModalController} from 'ionic-angular';
import { NativeStorage } from '@ionic-native/native-storage';
import {FormBuilder, FormGroup, Validators, AbstractControl} from '@angular/forms';
import { Camera} from '@ionic-native/camera';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { ImagePicker } from '@ionic-native/image-picker';
import { Crop } from '@ionic-native/crop';
import { Http, Response } from '@angular/http';
const URL = "http://192.168.43.50:8000/upload/trade";

 NewImage()
  {
    let imageActionSheet = this.actionSheet.create({
      title:"Select Image Source",

      buttons:[
        {
          text:"Use Camera",
          handler:()=>{
           // this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY)
           this.takePicture();
          }
        },
        {
          text:"Choose from Gallery",
          handler:()=>{
            this.browsePicture()

          }
        },
        {
          text:'Cancel',
          role:'cancel'
        }
      ]
    });
    imageActionSheet.present();
  }

  public takePicture(){
    var options = {
      quality :70,
      destinationType: this.camera.DestinationType.FILE_URI,
      saveToPhotoAlbum:false,
      correctOrientation:true,      
      sourceType:this.camera.PictureSourceType.CAMERA,
      encodingType: this.camera.EncodingType.JPEG

    }; 
    this.camera.getPicture(options).then(data=>{
      this.UploadImage(data)   
    }).catch((err)=>{
      console.log("Camera error :", err)
    }
    )
  }
  UploadImage(imagePath){
    const fileTransfer: FileTransferObject = this.transfer.create();
    let imageURI = imagePath.split('?').shift()
    let loader = this.loadingScreen.create({
      content:"Uploading. Please wait"
    });
    let options = {
      fileKey: "file",
      fileName: 'profilepic',
      chunkedMode: false,
      mimeType: 'image/jpeg',


    };
   //this.formData = new FormData()

    //this.formData.append('photo',{imageURI})
    loader.present();
    //     this.http.post(URL,this.formData).map((res:Response)=>res.json()).subscribe((success)=>{
    //   console.log(success._body);
    // },(error)=>{console.log(error);loader.dismiss()})

    fileTransfer.upload(imageURI,URL,options).then((entry) => {

       console.log("Upload Method");
      }, (err) => {
        loader.dismiss();
        console.log("uplaod error>",JSON.stringify(err)
      );
      });
 }

我无法理解,问题可能在哪里?任何指针都会非常有用。

1 个答案:

答案 0 :(得分:0)

请检查以下功能以获取图库中的图像

getFromGallery(){
var that = this;
const options: CameraOptions = {
    quality: 100,
    destinationType: this.camera.DestinationType.DATA_URL,
    encodingType: this.camera.EncodingType.JPEG,
    saveToPhotoAlbum: false,
    sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}
this.camera.getPicture(options).then((imageData) => {
    that.imageUrl = "data:image/jpeg;base64," + imageData.replace(/(\r\n|\n|\r)/gm, '');
    that.imageDataUrl = "data:image/jpeg;base64," + imageData.replace(/(\r\n|\n|\r)/gm, '');
}, (err) => {
    console.log(err);
});
}

借助上述功能,我们将在变量中获取图像数据。那么这个值就是后端。并在

中写入数据
uploadImage = function(req, res){
var return_val = {};
var imageData = req.body.profile_image;
imageBuffer = decodeBase64Image(imageData);
var imageType = imageBuffer.type;

var typeArr = new Array();
typeArr = imageType.split("/");

var fileExt = typeArr[1];

    if((fileExt === 'jpeg') || (fileExt === 'JPEG') || (fileExt === 'JPG') || (fileExt === 'jpg') || (fileExt === 'PNG') || (fileExt === 'png')) {
    if (imageBuffer.error) return imageBuffer.error;
    var image_name = Date.now()+"_"+req.user._id + '.'+ fileExt;
    var imagePath = "public/uploads/profileImage/"+image_name;
}    
fs.writeFile(imagePath, imageBuffer.data, function(imgerr, img) {
    if (imgerr) {
        res.json(imgerr);
    } 
    else {

        userModel.findOneAndUpdate({"_id":req.user._id},{$set:{"profile_image":image_name}}, function(errUpdate, dataUpdate){
            if(errUpdate){
                return_val.success = false;
                res.json(return_val);
            }
            else{

                //code to unlink previous file
                fs.unlink("public/uploads/profileImage/"+dataUpdate.profile_image, function(errDel, dataDel){
                    if(errDel){
                        console.log(errDel);
                    }
                    else{
                        return_val.profile_image = image_name;
                        return_val.success = true;
                        res.json(return_val);        
                    }
                });
                //End of code to unlink previous file 


            }
        });
    }

});

}