使用Cordova FileTransfer到NodeJS

时间:2017-06-23 20:25:23

标签: node.js cordova file-transfer

我目前正在使用Phonegap应用,我希望用户能够将任何文件上传到我的NodeJS服务器。

我一直在寻找网络,但我无法获得任何工作......

以下是我用于Phonegap控制器的代码:

$scope.open = function()
{
        navigator.camera.getPicture(upload, 
        function(message) 
        {
            alert('get picture failed');
        }, 
        { 
            quality: 50,
            destinationType: navigator.camera.PictureSourceType.FILE_URI,
            sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
            mediaType: navigator.camera.MediaType.ALLMEDIA  
        });

    }

    var win = function (r) {
        $scope.log = "Code = " + r.responseCode;
        $scope.log2 = "Response = " + r.response;
        $scope.log3 = "Sent = " + r.bytesSent;
        $scope.$digest();  

    }

    var fail = function (error) {
        $scope.log = "An error has occurred: Code = " + error.code;
        $scope.log2 = "upload error source " + error.source;
        $scope.log3 = "upload error target " + error.target;
        $scope.$digest();  
    }

    function upload(fileURI)
    {
        $scope.log = fileURI;
        $scope.$digest();  

        var options = new FileUploadOptions();
        options.fileKey = "file";
        options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
        options.mimeType = "text/plain";
        options.chunkedMode = false;

        var params = {};
        params.value1 = "test";
        params.value2 = "param";
        options.params = params;

        var ft = new FileTransfer();
        ft.upload(fileURI, "http://192.168.192.111:2999/upload", win, fail, options);
    }.

这是NodeJS服务器的当前代码,尝试了很多不同的东西,都没有成功:

var express = require('express');
var http = require('http').Server(express);
var io = require('socket.io')(http);
var fs = require('fs');

var multer = require('multer');
var app = new express();


app.post('/upload', multer({dest: './uploads/'}).single('upl'), function(req, res)
{
  console.log(req.body);
  console.log(req.file);
})


http.listen(2999, function(){
  console.log('listening on *:2999');
});

在应用程序中,我曾经遇到过FileUploadOptions等没有定义的错误,但我通过将它们添加到cordova项目来解决这个问题。 此外,我使用离子1,如果这有助于任何人。

我确实不断收到错误代码1(上传错误源),即使我选择了一个真实的文件,但我看到链接是正确的(类似于我的Android设备上的/ storage / 0 / emulated / Downloads)。

此外,有时它也会给我错误3(上传目标源),我认为某种服务器找不到问题。

有什么明显的事情我做错了,我怎么能解决它?有没有更方便的方法,因为我最终想将它链接到MySQL数据库。

提前致谢!

1 个答案:

答案 0 :(得分:0)

var express=require('express');
var bodyParser=require('body-parser');
var formidable = require('formidable');
var util = require('util');
var app=express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var path=require('path');
var mysql =require('mysql');
var fs=require('fs');

app.use('/public',express.static(path.join(__dirname, 'public')));

var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password : '',
        port : 3306, //port mysql
        database:'xxxxx'
});
app.post('/data', function(req, res) {

 // create an incoming form object
  var form = new formidable.IncomingForm(),
        files = [],
        fields = [];
  // specify that we want to allow the user to upload multiple files in a single request
  form.multiples = true;

  // store all uploads in the /uploads directory
  form.uploadDir = path.join(__dirname, '/public/images/uploads');
  // every time a file has been uploaded successfully,
  // rename it to it's orignal name
  form.on('file', function(field, file) {
    if (path.extname(file.name)=='') {
        extension='.jpg';
    }
    else{
      extension=path.extname(file.name);
    }
    var oldpath = file.path;
    form.uploadDir = path.basename(file.name,extension).concat((Math.random()* 100),extension);               
    var newpath = './public/images/uploads/'+ path.basename(file.name,extension).concat((Math.random()* 100),extension);

    //fs.rename(file.path, path.join(form.uploadDir, file.name));
    fs.rename(oldpath, newpath);
  });
  form.on('field', function(field, value) {
      fields[field] = value;   
  });

  // log any errors that occur
  form.on('error', function(err) {
    console.log('An error has occured: \n' + err);
  });

  // once all the files have been uploaded, send a response to the client

//Call back at the end of the form.
form.on('end', function () {

    res.writeHead(200, {
        'content-type': 'text/plain'
    });
    res.write('received the data:\n\n');


   // console.log(fields.name+'-'+fields.nickname);
    var values={
          name:fields.name,
          nickname:fields.nickname,
          email:fields.email,
          password:fields.password,
          dob:fields.dob,
          gender:fields.gender,
          phoneno:fields.phone
      };

    connection.query('INSERT INTO users SET ?', values, function(err,req,res){
                        if(err){
                          console.log('Connection result error '+err);

                        }
                            else{
                        console.log('Success');     

                            }
                });

               res.end();  


});
  // parse the incoming request containing the form data
  form.parse(req);
});

//app.use(app.router);
app.listen(5000);