1. 程式人生 > >ionic專案之上傳下載資料

ionic專案之上傳下載資料

一,首先是上傳資料

記得在angularjs的controller中注入$http依賴

var data = {id: $scope.task_id, 
         	groupId: $scope.task_groupid, 
         	importance: $scope.priority_level, 
         	classname:$scope.classname, 
         	title: $scope.task_title, 
         	date: $scope.todo_date, 
         	detail: $scope.task_detail,
         	images:$scope.images_list,
         	name:$scope.name,
         	record:$scope.recordPath,
         	donedate:$scope.done_date}
        
         $http({
         	method: 'POST',
         	url: 'http://localhost:3000',
         	params:{
         		'require': data
         	}
         	
         }).success(function(data,status,headers,config){
         	
         }).error(function(data,status,headers,config){
         	
         });

$http方法中的data引數,服務端沒有接收成功

$http方法中的params引數,服務端接收成功

服務端接收方法是 url.parse(req.url, true).query.params

(params即是加在url?後的引數)

二,然後是下載資料

    //重新整理
    $scope.refresh = function(){
    	$http.get("http://localhost:3000/refresh")
    	.success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        
        alert("success");
        alert("["+data.substring(0,data.lastIndexOf(","))+"]");                                                                                                                                                                                                                                                                  
        TodoListService.deleteAndAddTask(JSON.parse("["+data.substring(0,data.lastIndexOf(","))+"]"));
        TodoListService.findByGroupId($stateParams.groupId).then(function(todolists) {
       
			$scope.todolists = todolists; //對應類別的所有資料list
		});
        
        })
    	.error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        alert("error "+data);

        });
    	
    	
//      .success(function(response) {
//
//          console.log(response);
//          alert(response);
//      });
           
    }

回撥的success方法中返回的data資料,即為伺服器response給客戶端的資料

注意:返回的json字串要保證符合json格式(一開始最外層沒加中括號就會報錯)

三,服務端程式碼

var http = require('http');
var url = require('url');
var util = require('util');
var fs = require('fs'); 

http.createServer(function(req, res){
	var urldata = req.url+"";
    var require;
	console.log('connet');
	if(urldata.substring(1) == "refresh")
	{
       console.log("refresh");
	   require = "";
	   fs.readFile('writefile.txt','utf8', function(err, data) { 
	    if (err) { 
		  console.error(err); 
	    } else { 
		  console.log(data); 
		
          res.end(data+"");
	    } 
       });
       
	}
	else
	{
	   console.log("add");
       require = url.parse(req.url, true).query.require+",";
	   fs.open('writefile.txt', 'a', function opend(err, fd) { 
	   if(err) { 
		   console.error(err); 
		   return; 
	   } 
	   var writeBuffer = new Buffer(require),
		   bufferPosition = 0,
		   bufferLength = writeBuffer.length,
		   filePosition = null;
	   fs.write(fd,
		     writeBuffer,
		     bufferPosition,
		     bufferLength,
		     filePosition,
		     function wrote(err,written){
	           if(err){throw err;}
			   //console.log(err);
			 });
       });
	}
	

}).listen(3000);

還有個問題

由於ionic有自己的服務用於啟動專案,它啟動了http://localhost:8100 的服務,而ionic專案訪問伺服器需要另外的埠

所以在電腦瀏覽器除錯時會報錯

 XMLHttpRequest cannot load http://localhost:3000/refresh. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

需要讓瀏覽器忽略跨域問題就行了,可以乾脆關閉所有安全策略,當然瀏覽器會提示你穩定性和安全性降低

如果不想每次啟動都用命令列,也可以把啟動引數新增到瀏覽器快捷方式裡:右鍵點選Chrome圖示,在“快捷方法”標籤頁的“目標”一欄新增啟動引數到末尾即可(先留一個空格)


專案地址(包括ionic專案和簡易node伺服器程式碼,伺服器程式碼只用到了server.js和writefile.txt)

http://download.csdn.net/detail/superjunjin/8487079

原專案來自於http://rensanning.iteye.com/blog/2072034