mercredi 18 février 2015

Upload large (mp3) file from android to node.js using POST

I want to upload an mp3 file from my application to a node.js . There are two parameters accepted by the node.js and those are email_address and the mp3 file.


Following is the code I used yet failed to achieve the required functionality.



<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(SERVER_PATH);

// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setConnectTimeout(30000);
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs

conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("user_file", fileName);
//conn.connect();

dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"user_email\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(EMAIL_ADDRESS);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\"user_file\";filename=\"" + fileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);

// create a buffer of maximum size
bytesAvailable = fileInputStream.available();

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

// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {

dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

}

// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

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

Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);

if(serverResponseCode == 200){

Toast.makeText(getApplicationContext() ,"File Upload Complete.",
Toast.LENGTH_SHORT).show();

}

//close the streams //
fileInputStream.close();
dos.flush();
dos.close();


When I run this code I get an exception. The exception object thrown is also null. Hence as a beginner to android I cannot find the issue.


Aucun commentaire:

Enregistrer un commentaire