使用ionic开发webapp进行文件上传与下载

1.添加依赖的插件

1.org.apache.cordova.file-transfer
https://github.com/apache/cordova-plugin-file-transfer
This plugin allows you to upload and download files.
This plugin defines global FileTransfer, FileUploadOptions Constructors.
Although in the global scope, they are not available until after the deviceready event.
Installation

cordova plugin add cordova-plugin-file-transfer


2. org.apache.cordova.file
https://github.com/apache/cordova-plugin-file
This plugin implements a File API allowing read/write access to files residing on the device.
Installation
cordova plugin add cordova-plugin-file

2.保证你的项目中已经集成并且引用了ngCordova插件在你的

app.controller('MyCtrl', function($scope, $timeout, $cordovaFileTransfer) {
  $scope.downloadFile = function() {
    var url = "http://your_ip_address/images/my.jpg";
    var filename = url.split("/").pop();
    alert(filename);
    var targetPath = cordova.file.externalRootDirectory + filename;
    var trustHosts = true
    var options = {};
   //url提交的服务器地址 targetPath提交图片的本地地址
 $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
      .then(function(result) {
        // Success!
        alert(JSON.stringify(result));//把对象转化成字符串
      }, function(error) {
        // Error
        alert(JSON.stringify(error));
      }, function (progress) {
        $timeout(function () {
          $scope.downloadProgress = (progress.loaded / progress.total) * 100;
        })
      });
 }
$scope.uploadFile = function() {
     var url = "http://your_ip_address/uploads/upload.php";
     //target path may be local or url
     var targetPath = "http://your_ip_address/images/my.jpg";
      var filename = targetPath.split("/").pop();
        var options = {
            fileKey: "file",
            fileName: filename,
            chunkedMode: false,
            mimeType: "image/jpg"
        };
  
  //url提交的服务器地址 targetPath提交图片的本地地址
$cordovaFileTransfer.upload(url, targetPath, options).then(function(result) { console.log("SUCCESS: " + JSON.stringify(result.response)); alert("success"); alert(JSON.stringify(result.response)); }, function(err) { console.log("ERROR: " + JSON.stringify(err)); alert(JSON.stringify(err)); }, function (progress) { // constant progress updates $timeout(function () { $scope.downloadProgress = (progress.loaded / progress.total) * 100; }) }); }});
 
  


你可能感兴趣的:(使用ionic开发webapp进行文件上传与下载)