2011-12-01 89 views
3

我正在開發Android應用程序。在創建這個問題之前,我搜索了很多帖子。我想用java中的socket從android手機上傳文件。服務器端應該是什麼樣的應用程序?假設在java.lang中寫入服務器端應該是什麼類型的項目?關於java應用程序的 ,我只知道服務器主機 - tomcat。使用插槽將文件從Android上傳到服務器

回答

2

你的情況(作爲服務器有tomcat)如果你有服務器的URL,那麼你可以使用HttpURLConnection上傳任何文件到服務器。在服務器端邏輯應該被寫入接收文件

HttpURLConnection connection = null; 
DataOutputStream outputStream = null; 
DataInputStream inputStream = null; 

String pathToOurFile = "/sdcard/file_to_send.mp3"; //complete path of file from your android device 
String urlServer = "http://192.168.10.1/handle_upload.do";// complete path of server 
String lineEnd = "\r\n"; 
String twoHyphens = "--"; 
String boundary = "*****"; 

int bytesRead, bytesAvailable, bufferSize; 
byte[] buffer; 
int maxBufferSize = 1*1024*1024; 

try 
{ 
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); 

URL url = new URL(urlServer); 
connection = (HttpURLConnection) url.openConnection(); 

// Allow Inputs & Outputs 
connection.setDoInput(true); 
connection.setDoOutput(true); 
connection.setUseCaches(false); 

// Enable POST method 
connection.setRequestMethod("POST"); 

connection.setRequestProperty("Connection", "Keep-Alive"); 
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); 

outputStream = new DataOutputStream(connection.getOutputStream()); 
outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd); 
outputStream.writeBytes(lineEnd); 

bytesAvailable = fileInputStream.available(); 
bufferSize = Math.min(bytesAvailable, maxBufferSize); 
buffer = new byte[bufferSize]; 

// Read file 
bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

while (bytesRead > 0) 
{ 
outputStream.write(buffer, 0, bufferSize); 
bytesAvailable = fileInputStream.available(); 
bufferSize = Math.min(bytesAvailable, maxBufferSize); 
bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
} 

outputStream.writeBytes(lineEnd); 
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

// Responses from the server (code and message) 
serverResponseCode = connection.getResponseCode(); 
serverResponseMessage = connection.getResponseMessage(); 

fileInputStream.close(); 
outputStream.flush(); 
outputStream.close(); 
} 
catch (Exception ex) 
{ 
//Exception handling 
} 
+0

+1優秀的文章,也許人們所預料的服務器端,以配合這將是有益的什麼樣的代碼的簡要概述我。 – Elemental

+0

Sunil,通過你的解決方案,這是否意味着我需要創建一個web服務或網站來接收文件?有沒有辦法從服務器端沒有代碼的客戶端獲取文件?像FTP一樣? – user418751

+0

檢查SPK的FTP上傳鏈接。它鏈接到一個預製的FTP類爲您做上傳。但請記住,使用標準的FTP上傳可能是不安全的(因爲任何人都可能竊取登錄數據並濫用服務器!)。 – Mario

相關問題