Android:How to Upload .Mp3 File to Http Server

Android:How to upload .mp3 file to http server?

My final working JAVA and PHP code to upload a file from the Android's SD card to my own Web Server.

The Java/Android Code:

private void doFileUpload() {

HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mypic.png";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
String urlString = "http://mywebsite.com/directory/upload.php";

try {

//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// 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");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + 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);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();

} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}

//------------------ read the SERVER RESPONSE
try {

inStream = new DataInputStream(conn.getInputStream());
String str;

while ((str = inStream.readLine()) != null) {

Log.e("Debug", "Server Response " + str);

}

inStream.close();

} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}

The associated PHP code to go on your server (upload.php):

<?php
// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
chmod ("uploads/".basename( $_FILES['uploadedfile']['name']), 0644);
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>

Things to note.

1) I had "mypic.png" within the root directory of the SD card. As in, if you looked at the Android device through Mass Storage USB view you would put the file in the first directory you come across.

2) USB MASS STORAGE MUST BE TURNED OFF ON THE PHONE! Or just completely unplug it from the computer you are writing the code on to assure this is the case.

3) I had to create an "uploads" folder in the same directory as my php file.

4) You obviously must change the web address I have written as http://mywebsite.com/directory/upload.php to be your own website.

How to upload .mp3 file and image to http server?

So, you want to send multiple files in one HTTP request? I've never done this myself, but according to the RFC, just add another body to the message in which you send the audio, it should look something like this:

    dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// Code for sending the image....
dos.writeBytes(lineEnd);

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file_name_audio\";filename=\""
+ fileNameAudio + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// Code for sending the MP3
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

Make sure that the names of both parts are different (depending on the server software).

upload an image and audio in One request in android

Just use the httpmime-4.0.jar and apache-mime4j-0.4.jar and set the entity as MultipartEntity.
you can use as many file as you want.

Here is the stuff,

HttpPost httpost = new HttpPost("url for upload file");

MultipartEntity entity = new MultipartEntity();
entity.addPart("myIdentifier", new StringBody("somevalue"));
entity.addPart("myImageFile", new FileBody(imageFile));
entity.addPart("myAudioFile", new FileBody(audioFile));

httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);

and for php side you can use these entity identifier names "myImageFile" and "myAudioFile" and move these files in appropriate folder.

Working code for uploading mp3 to server on android

You can use loopj Android Asynchronous Http Client lib for uploading file to the php server.
download the lib file from given link and put into your project's libs folder and use this code for uploading file.

public void postFile(){
RequestParams params = new RequestParams();
params.put("fileTitle","MyFile1");
params.put("file", new File("File Path Here")); // e.g Environment.getExternalStorageDirectory().getPath() + "/test.mp3"

AsyncHttpClient client = new AsyncHttpClient();

client.post("http://www.yourweserviceurlhere.com", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
// TODO Auto-generated method stub

}

@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
// TODO Auto-generated method stub

}
});
}

if you want progress of uploading. then you can use my custom design class. for this also require common io 2.4 lib reference in converting HTTPresponse into string.

public class AsyncLoader {
private String url;
private LoaderCallBackHandler mCallback;
private Context mContext;
private RequestParams params;
private RequestHandle handle;

public interface LoaderCallBackHandler {
public void onStartUploading();
public void uploadComplete(String response);
public void failedWithError(Throwable error);
public void progressUpdate(long bytesWritten, long bytesTotal);
public void onCancle();
public void onFinish();
}

public AsyncLoader(Context mContext,String url,RequestParams params, LoaderCallBackHandler callback) {
this.mContext = mContext;
this.url = url;
this.params = params;
this.mCallback = callback;

}

public void startTransfer() {
AsynchConfig.mClient.setTimeout(50000);
handle = AsynchConfig.mClient.post(mContext, url, params,handlerInterface);
}
private ResponseHandlerInterface handlerInterface = new ResponseHandlerInterface() {

@Override
public void sendStartMessage() {
if(mCallback != null) {
mCallback.onStartUploading();
}

}

@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();

// TODO convert in stream to JSONObject and do whatever you need to

StringWriter writer = new StringWriter();
IOUtils.copy(instream, writer, Charset.defaultCharset());
String theString = writer.toString();

if(mCallback != null) {
mCallback.uploadComplete(theString);
}
}

}

@Override
public void sendSuccessMessage(int arg0, org.apache.http.Header[] arg1, byte[] arg2) {

}

@Override
public void sendFailureMessage(int arg0, org.apache.http.Header[] arg1,
byte[] arg2, Throwable error) {
if(mCallback != null) {
mCallback.failedWithError(error);
}
}

@Override
public void sendFinishMessage() {
if(mCallback != null) {
mCallback.onFinish();
}
}

@Override
public void sendProgressMessage(long bytesWritten, long bytesTotal) {
if(mCallback != null) {
mCallback.progressUpdate(bytesWritten, bytesTotal);
}

}

@Override
public void setUseSynchronousMode(boolean arg0) {
}

@Override
public void setRequestURI(URI arg0) {
}

@Override
public void setRequestHeaders(org.apache.http.Header[] arg0) {
}

@Override
public URI getRequestURI() {
return null;
}
@Override
public org.apache.http.Header[] getRequestHeaders() {
return null;
}

@Override
public void sendCancelMessage() {

if(mCallback != null) {
mCallback.onCancle();
mCallback.onFinish();
}
}

@Override
public void sendRetryMessage(int retryNo) {
// TODO Auto-generated method stub

}

@Override
public boolean getUseSynchronousMode() {
// TODO Auto-generated method stub
return false;
}

@Override
public void setUsePoolThread(boolean usePoolThread) {
// TODO Auto-generated method stub

}

@Override
public boolean getUsePoolThread() {
// TODO Auto-generated method stub
return false;
}

@Override
public void onPreProcessResponse(ResponseHandlerInterface instance,
HttpResponse response) {
// TODO Auto-generated method stub

}

@Override
public void onPostProcessResponse(ResponseHandlerInterface instance,
HttpResponse response) {
// TODO Auto-generated method stub

}

@Override
public void setTag(Object TAG) {
// TODO Auto-generated method stub

}

@Override
public Object getTag() {
// TODO Auto-generated method stub
return null;
}
};

/**
* Cancel upload by calling this method
*/
public void cancel() throws Exception {
AsynchConfig.mClient.cancelAllRequests(true);
handle.cancel(true);

}
}

Asynch config class

public final class AsynchConfig {   
public static AsyncHttpClient mClient = new AsyncHttpClient();
}

Use

RequestParams params = new RequestParams();
params.put("fileTitle","MyFile1");
params.put("file", new File("File Path Here")); // e.g Environment.getExternalStorageDirectory().getPath() + "/test.mp3"

AsyncLoader asyncUploader = new AsyncLoader(this, "URL_HERE", params, callHandler);
asyncUploader.startTransfer();

CallHandler Interface object

LoaderCallBackHandler callHandler = new LoaderCallBackHandler() {

@Override
public void uploadComplete(String response) {
// TODO Auto-generated method stub

}

@Override
public void progressUpdate(long bytesWritten, long bytesTotal) {
// TODO Auto-generated method stub

}

@Override
public void onStartUploading() {
// TODO Auto-generated method stub

}

@Override
public void onFinish() {
// TODO Auto-generated method stub

}

@Override
public void onCancle() {
// TODO Auto-generated method stub

}

@Override
public void failedWithError(Throwable error) {
// TODO Auto-generated method stub

}
};

PHP service for handling uploaded file

if(isset($_FILES['file']) && isset($_POST['fileTitle']) ) {
include './config.php';

//Randomly genrate file name
$stickerTmp = explode(".", $_FILES["file"]["name"]);
$file = md5(date("l, F d, Y h:i" ,time()) . (microtime())).".".end($stickerTmp);

//geting the temp location of file
$filetemploc=$_FILES['file']['tmp_name'];

//path for uploading to the specific location
$pathandname="file_store/".$file;

// moving the file to specified path
$resultUpload = move_uploaded_file($filetemploc, $pathandname);

// if file is successfully moved to over specified path then insert the reference into the DB
if($resultUpload == TRUE) {
//echo "File has been moved from : ". $filetemploc . " to :".$pathandname;

$qInsert = "INSERT INTO file_lists values (null,'".$_POST['fileTitle']."','".$file."') ";
mysql_query($qInsert);
}

}

How to upload audio to soundcloud via my android app using retrofit 2

Here example for upload image with retrofit 2.
First, when create retrofit for multipart request, doesn't add converter factory.

public static APIMultipartService getMultipartService() {
if (multipartService == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(DOMAIN)
.build();
multipartService = retrofit.create(APIMultipartService.class);
}
return multipartService;
}

Second, use RequestBody in interface.

public interface APIMultipartService {
@POST("/api/v1/job/photo/add")
Call<ResponseBody> uploadJobPhoto(@Body RequestBody body);}

And here example for create request body with file.

RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);

MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
builder.addFormDataPart("pic", "photo.png", body);
builder.addFormDataPart("jobId", id);
builder.addFormDataPart("privateKey", privateKey);

Call<ResponseBody> request = ApiService.getMultipartService().uploadJobPhoto(builder.build());
request.enqueue(callbackPhotoRequest);

Try like that, maybe help you.

streaming a mp3 from a site/server

Following line means: mMediaPlayer is null.

java.lang.NullPointerException: Attempt to invoke virtual method 
'void android.media.MediaPlayer.setDataSource(java.lang.String)'
on a null object reference

Please check mMediaplayer is initialized before onSuccess(Uri uri) method is called.

mMediaplayer = new MediaPlayer();


Related Topics



Leave a reply



Submit