cordova file transfer plugin not working in ios simulator

删除回忆录丶 提交于 2019-12-01 22:35:15

File Upload: Cordova File Transfer Plugin + ExpressJs Multer

The solution below lets me take a photo with the iPhone camera, and then uploads the photo to a NodeJS server.

@Kyokasuigetsu - almost gave up on FILE_URI with Cordova's File Transfer Plugin as well!


Notice that options.fileKey = 'myPhoto' and upload.single('myPhoto') should have the same value. It refers to the field name for the file upload form.

<!-- Upload a single file -->
<form>  
  <input type="file" name="myPhoto" />
</form>

Install needed plugins and modules (from console)

> cordova plugin add cordova-plugin-file-transfer;
> npm install express multer --save;

Cordova (native_app.js)

function uploadPhoto(fileUri) {
  // file:///var/mobile/Containers/Data/Application/
  // .../tmp/cdv_photo.jpg
  console.log("fileUri:", fileUri);

  var options, request;

  options = new FileUploadOptions();
  // The name 'fileKey' is confusing; it should be 'fieldname'
  options.fileKey = 'myPhoto';
  // fileName: 'cdv_photo.jpg';
  options.fileName =
    fileUri.substr(fileUri.lastIndexOf('/') + 1);

  request = new FileTransfer();
  request.upload(
    fileUri,
    encodeURI('http://localhost:8080/photos'),
    function success(response) {
      console.log("Success: Photo uploaded to server!");
    },
    function error(response) {
      console.log("Error: Photo not uploaded to server!");
    },
    options
  );
}

function capturePhoto(callback) {

  navigator.camera.getPicture(
    function success(fileUri) {
      callback(fileUri);
    },
    function error() {},
    { // camera options
      destinationType: Camera.DestinationType.FILE_URI,
      sourceType: Camera.PictureSourceType.CAMERA,
      encodingType: Camera.EncodingType.JPEG,
      mediaType: Camera.MediaType.PICTURE
    }
  );

}

function captureAndUploadPhoto() {
  capturePhoto(function (fileUrl) {
    uploadPhoto(fileUrl);
  });
}

document.addEventListener("deviceready", captureAndUploadPhoto, false);

NodeJs / ExpressJs (server_app.js)

var express, application, multer, upload;

express = require('express');
application = express();
multer  = require('multer');
upload = multer({dest: 'uploads/'}).single('myPhoto');

application.get('/photos', upload, function (request, response) {
  console.log(response.file);
  response.status(204).end();
});

application.listen(8080, function () {
  console.log('Example application listening on port 8080!');
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!