使用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"
        };
  <pre name="code" class="javascript">  //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; }) }); }});
 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值