2011-08-27 5 views
0

나는 android와 함께 phonegap에서 일하고있다. 파일을 내 서버에 업로드하고 싶습니다. 나는이 링크에서 도움을 촬영 한 -실제 매개 변수는 어디에 전달됩니까?

package com.beetight; 

import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import android.net.Uri; 
import java.net.URL; 
import java.util.Iterator; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 
import android.webkit.CookieManager; 

import com.phonegap.api.Plugin; 
import com.phonegap.api.PluginResult; 

/** 
* @author matt 
* 
*/ 
public class FileUploader extends Plugin { 

/* (non-Javadoc) 
* @see com.phonegap.api.Plugin#execute(java.lang.String, org.json.JSONArray, java.lang.String) 
*/ 
@Override 
public PluginResult execute(String action, JSONArray args, String callbackId) { 

try { 
String server = args.getString(0); 
String file = args.getString(1); 
JSONObject params = args.getJSONObject(2); 

String fileKey = "file"; 
String fileName = "image.jpg"; 
String mimeType = "image/jpeg"; 
if(args.length() > 3) { 
fileKey = args.getString(3); 
} 
if(args.length() > 4) { 
fileName = args.getString(4); 
} 
if(args.length() > 5) { 
mimeType = args.getString(5); 
} 

if (action.equals("upload")) { 
upload(file, server, params, fileKey, fileName, mimeType, callbackId); 
} else if (action.equals("uploadByUri")) { 
Uri uri = Uri.parse(file); 
upload(uri, server, params, fileKey, fileName, mimeType, callbackId); 
} else { 
return new PluginResult(PluginResult.Status.INVALID_ACTION); 
} 
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); 
r.setKeepCallback(true); 
return r; 
} catch (JSONException e) { 
e.printStackTrace(); 
return new PluginResult(PluginResult.Status.JSON_EXCEPTION); 
} 

} 

public void upload(Uri uri, String server, JSONObject params, final String fileKey, final String fileName, final String mimeType, String callbackId) { 
try { 
InputStream fileInputStream=this.ctx.getContentResolver().openInputStream(uri); 
upload(fileInputStream, server, params, fileKey, fileName, mimeType, callbackId); 
} catch (FileNotFoundException e) { 
Log.e("PhoneGapLog", "error: " + e.getMessage(), e); 
} 
} 

public void upload(String filename, String server, JSONObject params, final String fileKey, final String fileName, final String mimeType, String callbackId) { 
File uploadFile = new File(filename); 
try { 
FileInputStream fileInputStream = new FileInputStream(uploadFile); 
upload(fileInputStream, server, params, fileKey, fileName, mimeType, callbackId); 
} catch (FileNotFoundException e) { 
Log.e("PhoneGapLog", "error: " + e.getMessage(), e); 
} 

} 


public void upload(InputStream fileInputStream, String server, JSONObject params, final String fileKey, final String fileName, final String mimeType, final String callbackId) { 
try { 

String lineEnd = "\r\n"; 
String td = "--"; 
String boundary = "*****com.beetight.formBoundary"; 

URL url = new URL(server); 
HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 

// Get cookies that have been set in our webview 
CookieManager cm = CookieManager.getInstance(); 
String cookie = cm.getCookie(server); 

// allow inputs 
conn.setDoInput(true); 
// allow outputs 
conn.setDoOutput(true); 
// don't use a cached copy 
conn.setUseCaches(false); 
// use a post method 
conn.setRequestMethod("POST"); 
// set post headers 
conn.setRequestProperty("Connection","Keep-Alive"); 
conn.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary); 
conn.setRequestProperty("Cookie", cookie); 
// open data output stream 
DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); 

try { 
for (Iterator iter = params.keys(); iter.hasNext();) { 
Object key = iter.next(); 
dos.writeBytes(td + boundary + lineEnd); 
dos.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"; "); 
dos.writeBytes(lineEnd + lineEnd); 
dos.writeBytes(params.getString(key.toString())); 
dos.writeBytes(lineEnd); 
} 
} catch (JSONException e) { 
Log.e("PhoneGapLog", "error: " + e.getMessage(), e); 
} 


dos.writeBytes(td + boundary + lineEnd); 
dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";filename=\"" + fileName + "\"" + lineEnd); 
dos.writeBytes("Content-Type: " + mimeType + lineEnd); 

dos.writeBytes(lineEnd); 
// create a buffer of maximum size 
int bytesAvailable = fileInputStream.available(); 
final int total = bytesAvailable; 
Log.e("PhoneGapLog", "available: " + bytesAvailable); 

int maxBufferSize = 1024; 
int bufferSize = Math.min(bytesAvailable, maxBufferSize); 
byte[] buffer = new byte[bufferSize]; 
// read file and write it into form... 
int bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
int progress = bytesRead; 
int send = 0; 
while (bytesRead > 0) 
{ 
dos.write(buffer, 0, bufferSize); 
bytesAvailable = fileInputStream.available(); 
bufferSize = Math.min(bytesAvailable, maxBufferSize); 
bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
progress += bytesRead; 
final int prog = progress; 
Log.e("PhoneGapLog", "read " + progress + " of " + total); 

// Sending every progress event is overkill 
if (send++ % 20 == 0) { 
ctx.runOnUiThread(new Runnable() { 
public void run() { 
try { 
JSONObject result = new JSONObject(); 
result.put("status", FileUploader.Status.PROGRESS); 
result.put("progress", prog); 
result.put("total", total); 
PluginResult progressResult = new PluginResult(PluginResult.Status.OK, result); 
progressResult.setKeepCallback(true); 
success(progressResult, callbackId); 
} catch (JSONException e) { 
Log.e("PhoneGapLog", "error: " + e.getMessage(), e); 
} 
} 
}); 
// Give a chance for the progress to be sent to javascript 
Thread.sleep(100); 
} 
} 
// send multipart form data necessary after file data... 
dos.writeBytes(lineEnd); 
dos.writeBytes(td + boundary + td + lineEnd); 

// close streams 
fileInputStream.close(); 
dos.flush(); 
InputStream is = conn.getInputStream(); 
int ch; 
StringBuffer b =new StringBuffer(); 
while((ch = is.read()) != -1) { 
b.append((char)ch); 
} 
String s=b.toString(); 
dos.close(); 
JSONObject result = new JSONObject(); 
result.put("status", FileUploader.Status.COMPLETE); 

result.put("progress", progress); 
result.put("total", total); 
result.put("result", s); 
PluginResult progressResult = new PluginResult(PluginResult.Status.OK, result); 
progressResult.setKeepCallback(true); 
success(progressResult, callbackId); 

} 
catch (MalformedURLException e) { 
Log.e("PhoneGapLog", "error: " + e.getMessage(), e); 
PluginResult result = new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION, e.getMessage()); 
error(result, callbackId); 
} 
catch (FileNotFoundException e) { 
Log.e("PhoneGapLog", "error: " + e.getMessage(), e); 
PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage()); 
error(result, callbackId); 
} 
catch (IOException e) { 
Log.e("PhoneGapLog", "error: " + e.getMessage(), e); 
PluginResult result = new PluginResult(PluginResult.Status.IO_EXCEPTION, e.getMessage()); 
error(result, callbackId); 
} catch (InterruptedException e) { 
Log.e("PhoneGapLog", "error: " + e.getMessage(), e); 
PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage()); 
error(result, callbackId); 
} catch (JSONException e) { 
Log.e("PhoneGapLog", "error: " + e.getMessage(), e); 
PluginResult result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); 
error(result, callbackId); 
} 
} 

public enum Status { 
PROGRESS, 
COMPLETE 
} 


} 

이는 다음과 같습니다 :이 클래스 내 fileuploader.java

package com.beetight; 

import com.phonegap.*; 
import android.os.Bundle; 

public class fileupload extends DroidGap { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     super.loadUrl("file:///android_asset/www/index.html"); 
    } 
} 

입니다 https://github.com/purplecabbage/phonegap-plugins/tree/master/Android/FileUploader

이 내 fileupload.java 코드 내 index.html :

<!DOCTYPE HTML> 
<html> 
    <head> 
    <meta name="viewport" content="width=320; user-scalable=no" /> 
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"> 
    <title>PhoneGap Demo With JQuery Mobile</title> 
     <link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.0b2.css" type="text/css" charset="utf-8" /> 
     <link rel="stylesheet" href="pgandjqm-style-override.css" type="text/css" charset="utf-8" /> 
     <script type="text/javascript" src="jquery.mobile/jquery-1.6.2.min"></script> 
     <script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script> 
     <script src="jquery.mobile/jquery.mobile-1.0b2.js"></script> 
     <script type="text/javascript" charset="utf-8" src="main.js"></script> 

    <!-- CDN Respositories: For production, replace lines above with these uncommented minified versions --> 
    <!-- <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" />--> 
    <!-- <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>--> 
    <!-- <script src="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"></script>--> 
    <script type="text/javascript" charset="utf-8" src="fileuploader.js"></script> 
    </head> 
    <body> 
    <h1>file uploader</h1> 
    </body> 
</html> 

이 내 fileuploader.js입니다 :

FileUploader.prototype.uploadByUri = function(server, file, params, fileKey, fileName, mimeType, callback, fail) { 

    return PhoneGap.exec(function(args) { 
     callback(args); 
    }, function(args) { 
if(typeof fail == 'function') { 
fail(args); 
} 
    }, 'FileUploader', 'uploadByUri', [server, file, params, fileKey, fileName, mimeType]); 
}; 
FileUploader.prototype.upload = function(server, file, params, fileKey, fileName, mimeType, callback, fail) { 

    return PhoneGap.exec(function(args) { 
if(typeof callback == 'function') { 
callback(args); 
} 
    }, function(args) { 
if(typeof fail == 'function') { 
fail(args); 
} 
    }, 'FileUploader', 'upload', [server, file, params, fileKey, fileName, mimeType]); 
}; 


FileUploader.Status = { 
PROGRESS: "PROGRESS", 
COMPLETE: "COMPLETE" 
} 

PhoneGap.addConstructor(function() { 
PhoneGap.addPlugin('fileUploader', new FileUploader()); 
PluginManager.addService("FileUploader","com.beetight.FileUploader"); 
}); 

이 내 전체 코드입니다 ..하지만 난 다음이 프로젝트를 실행 할 때마다 내가 아무것도하지 않습니다. 내가 어디 서버에 업로드하려는 내 서버 이름, 파일의 실제 매개 변수를 전달 해야할지 모르겠다. 그래서 내 서버 이름과 그 파일의 이름을 서버에 업로드하고 싶으면 어떻게 제안 해주십시오. 나는 phonegap 프로그램에서 매우 신선하다. 미리 알려주세요.

답변

0

이 코드를 감안할 때 그것은 기대

var uploader = FileUploader(); 
uploader.upload("http://yourserver-here.com", //<-- this is where you put your server 
     "myfile.txt", //<-- The file you want to upload 
     {} , //Not sure what this parameters is for, perhaps adding QS to server path 
     "file", //Filekey, using the default from Fileuploader.java 
     "myfile.txt", //filename 
     "text/plain", //file mime-type 
     function(args) {  //callback. 
      alert("Callback"); //Not sure if this means success or if you have to check args 
     }, 
     function(args) {  //callback on failure. 
      alert("Failed"); 
     }); 
같은
관련 문제