Application crashes when I save image to SD card - android

I am trying to use a simple image view and download application, everything works fine till I click on the button to download the application, the moment I click on the button, I get an error saying the application has been closed because it stopped working.
package com.theappguruz.imagedownload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.SQLException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import com.theappguruz.R;
public class ImageViewAndDownload extends Activity implements OnClickListener {
private Button btnImageDownload;
private ProgressDialog pd;
private ImageView viewDownloadImage;
private Images imageId;
private File folderName;
private String imageName;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
if (pd != null) {
pd.dismiss();
}
Utils.showNetworkAlert(ImageViewAndDownload.this);
} else if (msg.what == 2) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image downloade succesfully",
ImageViewAndDownload.this);
// Media scaning
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
} else if (msg.what == 3) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image already downloaded ",
ImageViewAndDownload.this);
} else if (msg.what == 4) {
if (pd != null) {
pd.dismiss();
}
displayImageFromUrl((Bitmap) msg.obj);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagedisplay);
viewDownloadImage = (ImageView) findViewById(R.id.viewImage);
btnImageDownload = (Button) findViewById(R.id.btnImageDownload);
imageId = new Images();
imageName = imageId.getImageId();
LoadImageFromWeb(Constant.IMAGE_BASE_URL + File.separator + imageName);
btnImageDownload.setOnClickListener(this);
}
public void onClick(View v) {
if (v == btnImageDownload) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Downloading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
String imageUrl = Constant.IMAGE_BASE_URL
+ File.separator + imageName;
String isDownloded = downloadImage(imageUrl, imageName);
if (isDownloded.equalsIgnoreCase("complete")) {
handler.sendEmptyMessage(2);
} else if (isDownloded.equalsIgnoreCase("")) {
handler.sendEmptyMessage(3);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
handler.sendEmptyMessage(1);
}
}
}).start();
}
}
// set display image to Imageview
public void displayImageFromUrl(Bitmap obj) {
viewDownloadImage.setImageBitmap(obj);
}
// image display from the webview
private void LoadImageFromWeb(final String url1) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Loading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
InputStream is = connection.getInputStream();
Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000
|| options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000
|| options.outHeight > 1000) {
options.inSampleSize = 2;
}
// Do the actual decoding
options.inJustDecodeBounds = false;
is.close();
is = getHTTPConnectionInputStream(url1);
Bitmap myBitmap = BitmapFactory.decodeStream(is, null,
options);
is.close();
if (myBitmap != null) {
Message msg = new Message();
msg.obj = myBitmap;
msg.what = 4;
handler.sendMessage(msg);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public InputStream getHTTPConnectionInputStream(String url1) {
URL url;
InputStream is = null;
try {
url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
is = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
// image download code
public String downloadImage(String imageDownloadUrl, String imageName) {
// create directory in SDCARD
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
folderName = new File(Constant.STORE_IN_FOLDER);
else
folderName = getFilesDir();
if (!folderName.exists())
folderName.mkdirs();
String response = "";
// create file name and file.
File storeImageInSDCard = new File(folderName + File.separator
+ imageName);
if (!(storeImageInSDCard.exists() && storeImageInSDCard.length() > 0)) {
// start download image
response = downloadFile(imageDownloadUrl, imageName,
folderName.toString());
}
return response;
}
// start download image
public String downloadFile(final String url, final String name,
String foldername) {
File file;
FileOutputStream os = null;
Bitmap myBitmap;
try {
URL url1 = new URL(url.replaceAll(" ", "%20"));
System.out.println("Image url :::" + url1);
HttpURLConnection urlConnection = (HttpURLConnection) url1
.openConnection();
urlConnection.setDoOutput(false);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// here create a file which define folder name and image name with
// extension.
file = new File(foldername, name + ".jpg");
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
os = new FileOutputStream(file);
while ((bufferLength = inputStream.read(buffer)) > 0) {
os.write(buffer, 0, bufferLength);
}
os.flush();
os.close();
// if image size is too large we can scale image than download.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000 || options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000 || options.outHeight > 1000) {
options.inSampleSize = 2;
}
options.inJustDecodeBounds = false;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
os = new FileOutputStream(file);
myBitmap.compress(CompressFormat.JPEG, 90, os);
os.flush();
os.close();
myBitmap.recycle();
return "complete";
} catch (SQLException e) {
e.printStackTrace();
return "error";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}
Link to the LogCat

You have:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
First, this was never something appropriate to use.
Second, it is blocked now, because it was never something appropriate to use, and now Google is stopping it on newer versions of Android.
The proper approach is to use MediaScannerConnection and its scanFile() method, or perhaps ACTION_MEDIA_SCANNER_SCAN_FILE.

Related

HttpURLConnection problem in Android Studio while loading an image from internet

I'm trying to download the image from URL: "http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png
and after that I want to display it in image view. but continuously the error in HttpURLConnection is occurring
On clicking of a button(download function is called) it should remove the previous image and load the new image from the url
I have tried using internet on emulator and its working fine. emulator and my pc is connected to internet. I have also asked permissions in AndroidMenifest. but nothing is solving the problem.
package com.example.web;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
public class ImageDownloader extends AsyncTask<String,Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} catch (IOException e) {
e.printStackTrace();
Log.i("Error","Error encountered");
}
return null;
}
}
public void download(View view) {
imageView = findViewById(R.id.imageView3);
imageView.setImageResource(0);
ImageDownloader imageDownloader = new ImageDownloader();
try {
Bitmap bitmap = imageDownloader.execute("http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png").get();
imageView.setImageBitmap(bitmap);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Permissions in AndroidMenifiest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
As Per Your Code I write Down New One just Replace it With Existing One
public class MainActivity extends AppCompatActivity {
ImageView imageView;
public class ImageDownloader extends AsyncTask<String,Void, Bitmap> {
OutputStream output;
#Override
protected Bitmap doInBackground(String... strings) {
int count;
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
try {
URL url = new URL(strings[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "DownloadedFile" + ts + ".jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int cur = (int) ((total * 100) / lenghtOfFile);
if (Math.min(cur, 100) > 98) {
try {
// Sleep for 5 seconds
Thread.sleep(500);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}
Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "\n " + cur);
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
public void download(View view) {
imageView = findViewById(R.id.imageView3);
imageView.setImageResource(0);
ImageDownloader imageDownloader = new ImageDownloader();
try {
Bitmap bitmap = imageDownloader.execute("http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png").get();
imageView.setImageBitmap(bitmap);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
If you want to download Image and store in Your Local Storage then Use Below Code.
Here I create One DownloadFileFromURL.class File which is my AsyncTask So downloading processed Without Interruption.
public DownloadFileFromURL(Context context) {
this.context = context;
}
protected void onPreExecute() {
super.onPreExecute();
Log.e(TAG, "onPreExecute: Download started");
}
#Override
protected String doInBackground(String... f_url) {
int count;
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "Your Folder Name" + ts + ".jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int cur = (int) ((total * 100) / lenghtOfFile);
if (Math.min(cur, 100) > 98) {
try {
// Sleep for 5 seconds
Thread.sleep(500);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}
Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "\n " + cur);
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
Now Call Above File in Your Activity or When You want. At the time of Calling this AsyncTask pass Your URLto download images.
new DownloadFileFromURL(context).execute("Your Download URL");

image is not saving to android device in Sd card

package com.lociiapp;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.example.imageslideshow.R;
public class recciverfullimageActivty extends Activity {
String reccvierid;
Context context;
ImageView recciverimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent myintent = getIntent();
reccvierid = myintent.getStringExtra("reccvierid");
recciverimage = (ImageView) findViewById(R.id.recciverImage);
String myfinalpathare = reccvierid;
Toast.makeText(getApplicationContext(), reccvierid, 10000).show();
String imagepathe = "http://api.lociiapp.com/TransientStorage/"
+ myfinalpathare + ".jpg";
try {
saveImage(imagepathe);
Log.e("****************************", "Sucess");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void saveImage(String urlPath) throws Exception {
String fileName = "test.jpg";
File folder = new File("/sdcard/LociiImages/");
// have the object build the directory structure, if needed.
folder.mkdirs();
final File output = new File(folder, fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
// InputStreamReader reader = new InputStreamReader(stream);
DataInputStream dis = new DataInputStream(url.openConnection()
.getInputStream());
byte[] fileData = new byte[url.openConnection().getContentLength()];
for (int x = 0; x < fileData.length; x++) { // fill byte array with
// bytes from the data
// input stream
fileData[x] = dis.readByte();
}
dis.close();
fos = new FileOutputStream(output.getPath());
fos.write(fileData);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
This is My code I am trying to save Image which is coming from server we have Image Url . when i Run this Code then Folder is creating in Sd card But image is not downloading on Save in Sd care please help and tell where i am doing wrong .
Your checklist should be as follows:
A. Make sure you have the right permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
B. Move networking and file IO logic to non-UI thread:
new AsyncTask<Params, Progress, Result>() {
#Override protected Result doInBackground() {
saveImage(imagepathe);
}
#Override protected void onPostExecute(String result) {
// update UI here
}
}.execute(params);
C. Do not read one byte at the time. It is probably not the source of your problem but it
does make your solution much slower than it can be:
Instead of:
for(;;) {
fileData[x] = dis.readByte();
}
Do this:
URL u = new URL(url);
URLConnection connection = u.openConnection();
byte[] buffer = new byte[connection.getContentLength()];
stream.readFully(buffer); // <------------- read all at once
stream.close();
D. And , finally, consider using Picasso for the job:
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
Nowadays you just no not need to write that much code to get were you're going..
Try this..
Call like below instead of saveImage(imagepathe);
myAsyncTask myWebFetch = new myAsyncTask();
myWebFetch.execute();
and myAsyncTask.class
class myAsyncTask extends AsyncTask<Void, Void, Void> {
public ProgressDialog dialog;
myAsyncTask()
{
dialog = new ProgressDialog(webview.this);
dialog.setMessage("Loading image...");
dialog.setCancelable(true);
dialog.setIndeterminate(true);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
protected Void doInBackground(Void... arg0) {
try {
InputStream stream = null;
URL url = new URL("http://api.lociiapp.com/TransientStorage/286.jpg");
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File myDir = new File(SDCardRoot + "/LociiImages");
myDir.mkdirs();
File file = new File(myDir,"test.jpg");
FileOutputStream fileOutput = new FileOutputStream(file);
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = stream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
EDIT
String imagePath = Environment.getExternalStorageDirectory().toString() + "/LociiImages/test.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageview.setImageBitmap(bitmap);

Uploading Images to Server android

I want to know which is the best way to upload image to server without losing its quality.
I have searched on google found various methods of posting data. But I am not sure which one would be best to upload.
I came across:
Multipart Image Upload.
Uploading images using byte array
Uploading images using base64 encoded string.
I have tried Base64 encoding it leads me to OOM(Out of memory) if image is too high in resolution.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
ABOVE CODE TO SELECT IMAGE FROM GALLERY
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
String filePath = getPath(selectedImage);
String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
image_name_tv.setText(filePath);
try {
if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
//FINE
} else {
//NOT IN REQUIRED FORMAT
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaColumns.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
NOW POST THE DATA USING MULTIPART FORM DATA
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("LINK TO SERVER");
Multipart FORM DATA
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (filePath != null) {
File file = new File(filePath);
Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
mpEntity.addPart("avatar", new FileBody(file, "application/octet"));
}
FINALLY POST DATA TO SERVER
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
Main activity class to take pick and upload
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class MainActivity extends Activity {
Button btpic, btnup;
private Uri fileUri;
String picturePath;
Uri selectedImage;
Bitmap photo;
String ba1;
public static String URL = "Paste your URL here";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btpic = (Button) findViewById(R.id.cpic);
btpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickpic();
}
});
btnup = (Button) findViewById(R.id.up);
btnup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
upload();
}
});
}
private void upload() {
// Image location URL
Log.e("path", "----------------" + picturePath);
// Image
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
//ba1 = Base64.encodeBytes(ba);
Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
private void clickpic() {
// Check Camera
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// Open default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, 100);
} else {
Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
selectedImage = data.getData();
photo = (Bitmap) data.getExtras().get("data");
// Cursor to get image uri to display
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
imageView.setImageBitmap(photo);
}
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Wait image uploading!");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop" + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
pd.dismiss();
}
}
}
php code to handle upload image and also create image from base64 encoded data
<?php
error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$fp = fopen($imgname, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
echo "Image uploaded";
}else{
echo "Error uploading image";
}
}
?>
use below code it helps you....
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
options.inPurgeable = true;
Bitmap bm = BitmapFactory.decodeFile("your path of image",options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
// bitmap object
byteImage_photo = baos.toByteArray();
//generate base64 string of image
String encodedImage =Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
//send this encoded string to server
Try this method for uploading Image file from camera
package com.example.imageupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds() {
if (!isSetFirst) {
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if (isSetLast) {
return;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
.getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName,
final InputStream fin) {
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName,
final InputStream fin, String type) {
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: " + type + "\r\n";
out.write(("Content-Disposition: form-data; name=\"" + key
+ "\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
}
public boolean isChunked() {
return false;
}
public boolean isRepeatable() {
return false;
}
public boolean isStreaming() {
return false;
}
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
public Header getContentEncoding() {
return null;
}
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
Use of class for uploading
private void doFileUpload(File file_path) {
Log.d("Uri", "Do file path" + file_path);
try {
HttpClient client = new DefaultHttpClient();
//use your server path of php file
HttpPost post = new HttpPost(ServerUploadPath);
Log.d("ServerPath", "Path" + ServerUploadPath);
FileBody bin1 = new FileBody(file_path);
Log.d("Enter", "Filebody complete " + bin1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploaded_file", bin1);
reqEntity.addPart("email", new StringBody(useremail));
post.setEntity(reqEntity);
Log.d("Enter", "Image send complete");
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
Log.d("Enter", "Get Response");
try {
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE", response_str);
JSONObject jobj = new JSONObject(response_str);
result = jobj.getString("ResponseCode");
Log.e("Result", "...." + result);
}
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
} catch (Exception e) {
Log.e("Upload Exception", "");
e.printStackTrace();
}
}
Service for uploading
<?php
$image_name = $_FILES["uploaded_file"]["name"];
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;
$flag=0;
if (file_exists("Images/".$new_image_name))
{
$msg=$new_image_name . " already exists."
header('Content-type: application/json');
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));
}else{
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
$flag = 1;
}
if($flag == 1){
require 'db.php';
$static_url =$new_image_name;
$conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
$db=mysql_select_db($db_database,$conn) or die("unable to select message_app");
$email = "";
if((isset($_REQUEST['email'])))
{
$email = $_REQUEST['email'];
}
$sql ="insert into alert(images) values('$static_url')";
$result=mysql_query($sql);
if($result){
echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
} else
{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
}
}
else{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));
}
?>
//Kotlin Version
private fun setImageForUploading (imagePath:String):String{
val options = BitmapFactory.Options();
options.inSampleSize = 2
//options.inPurgeable = true //deprecated
val bitmap = BitmapFactory.decodeFile(imagePath,options)
val byteArrayOutPutStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG,90,byteArrayOutPutStream)
// bitmap object
val byteImagePhoto = byteArrayOutPutStream.toByteArray()
//generate base64 string of image
val encodedImage = Base64.encodeToString(byteImagePhoto,Base64.DEFAULT)
return encodedImage
}

Code not hitting the server side

I am trying to send an image from android mobile to .NET server, android code:-
package com.example.imageupload;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
InputStream mInputStream;
String mUrl = "http://10.0.2.2:49246/WebSite1/";
// Async task helps to run network operations in Non-UI thread..
private class GetRouteInfo extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
//resize the bitmap...
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/android.jpg";
Bitmap bitmap = resizeBitMapImage1(path, 800, 600);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30, stream);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image_data", Base64.encodeToString(stream.toByteArray(),Base64.NO_WRAP)));
stream.flush();
stream.close();
bitmap.recycle();
nameValuePairs.add(new BasicNameValuePair("FileName", "TrueSeeImage"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mUrl);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response1 = httpclient.execute(httppost);
Log.i("response", response1.toString());
Log.i("DataUploaderOffline_Image ","Status--> Completed");
}
catch (Exception e) {
Log.i("SvcMgr", "Service Execution Failed!", e);
}
finally {
Log.i("SvcMgr", "Service Execution Completed...");
}
return null;
}
#Override
protected void onCancelled() {
Log.i("SvcMgr", "Service Execution Cancelled");
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.i("SvcMgr", "Service Execution cycle completed");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetRouteInfo().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
mInputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
System.out.println("contentLength : " + contentLength);
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = mInputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
mInputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
System.out.println("Result : " + res);
}
return res;
}
// Method to compress image..
// Input : filepath, target width, target height..
// Output : resized bitmap image..
public static Bitmap resizeBitMapImage1(String filePath, int targetWidth,int targetHeight) {
Bitmap bitMapImage = null;
try {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
double sampleSize = 0;
Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math
.abs(options.outWidth - targetWidth);
if (options.outHeight * options.outWidth * 2 >= 1638) {
sampleSize = scaleByHeight ? options.outHeight / targetHeight
: options.outWidth / targetWidth;
sampleSize = (int) Math.pow(2d,Math.floor(Math.log(sampleSize) / Math.log(2d)));
}
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[128];
while (true) {
try {
options.inSampleSize = (int) sampleSize;
bitMapImage = BitmapFactory.decodeFile(filePath, options);
break;
} catch (Exception ex) {
try {
sampleSize = sampleSize * 2;
} catch (Exception ex1) {
}
}
}
} catch (Exception ex) {
}
return bitMapImage;
}
}
And the .NET part is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(Server.MapPath("~/Data")))
{
}
else
{
System.IO.Directory.CreateDirectory(Server.MapPath("~/Data"));
}
if (Request.InputStream.Length != 0 && Request.InputStream.Length < 32768)
{
Response.ContentType = "text/plain";
string c = Request.Form["image_data"];
string FileName = Request.Form["FileName"];
byte[] bytes = Convert.FromBase64String(c);
System.Drawing.Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = System.Drawing.Image.FromStream(ms);
image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
String Fname = FileName + ".jpeg";
image.Save(Server.MapPath("save\\" + Fname), System.Drawing.Imaging.ImageFormat.Jpeg);
Response.End();
}
}
}
}
When I try to access the server side code from android browser it hits the server side code in the debug mode, but when I run the program from eclipse or debug the program from eclipse, it doesn't hit the code in the visual studio. What could be the reason?

how to send audio file from android client to servlet server

I want to send an audio file .mp3 file from android client to servlet server and save it in a location. If I play that saved .mp3 file in that location it should play.
My question is there a way to send a .mp3 file directly from client to server and retrieve that mp3 file in servlet.
My client side code is as follows:
package com.android.audiorecord;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.android.audiofileplayer.StreamingMp3Player;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
public class AudioRecordActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private String url = "QRFileSaveServlet";
String result;
byte[] value;
String s;
byte[] filebyte,clientbyte;
String readString;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private SubmitButton mSubmitButton = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
String fileresult = "";
HttpResponse response;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
/* public boolean saveas(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/media/audio/ringtones/";
String filename="examplefile"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
} */
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
// mRecorder.reset();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
class SubmitButton extends Button {
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
File f = new File(Environment.getExternalStorageDirectory()+"/audiorecordtest.mp3");
//
//byte[] file = fileresult.getBytes();
try {
filebyte = FileUtils.readFileToByteArray(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("$$$$$$$$$$$" + filebyte);
clientbyte = Base64.encode(filebyte, MODE_APPEND);//(filebyte, MODE_APPEND);
s= new String(clientbyte);
System.out.println("**************" + s);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Audiofile", s));
result = AudioServer.executePost(url, nameValuePairs);
result = result.trim();
System.out.println("response recieved " + result);
if(result!=null){
Bundle bundle = new Bundle();
Intent explicitIntent = new Intent(AudioRecordActivity.this,
StreamingMp3Player.class);
bundle.putString("result", result);
explicitIntent.putExtras(bundle);
startActivity(explicitIntent);
}
}
};
public SubmitButton(Context ctx) {
super(ctx);
setText("Save");
setOnClickListener(clicker);
}
}
public AudioRecordActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.mp3";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mSubmitButton = new SubmitButton(this);
ll.addView(mSubmitButton, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
in this can i send audiorecordtest.mp3 file direcly to server without encoding to byte[] and send it in namevalue pair.
My server side code is as follows:
package com.gsr.qrbarcode;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import com.android.gsr.utils.AudioSampleReader;
import com.android.gsr.utils.AudioSampleWriter;
import com.android.gsr.utils.Base64;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFileFormat.Type;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.apache.commons.io.FileUtils;
/**
* Servlet implementation class QRFileSaveServlet
*/
//#WebServlet("/QRFileSaveServlet")
public class QRFileSaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
AudioInputStream ais;
/**
* Default constructor.
*/
public QRFileSaveServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String qrfile= request.getParameter("Audiofile");
System.out.println("String Parameter \"" +qrfile );
byte[] audiofile=Base64.decode(qrfile);
String newStr = new String(audiofile);
// Display the contents of the byte array.
System.out.println("The new String equals \"" +newStr + "\"");
String filePath = this.getServletContext().getRealPath("/")+"";
System.out.println("Path of the file " + filePath);
String fileupload="AudioFileStorage";
//PrintWriter out = response.getWriter();
File f;
f= new File(filePath);
//int status = 0;
if(f.exists()) {
filePath += fileupload;
f = new File(filePath);
if(!f.exists()){
f.mkdir();
}
f = new File(filePath,"test.mp3");
if(!f.exists()) {
FileOutputStream fos = new FileOutputStream(f);
fos.write(audiofile);
fos.flush();
fos.close();
} else {
//out.println("failure");
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try{
stream = response.getOutputStream();
// File mp3 = new File(mp3Dir + "/" + fileName);
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition","attachment; filename="+f );
response.setContentLength( (int) f.length() );
FileInputStream input = new FileInputStream(f);
buf = new BufferedInputStream(input);
int readBytes = 0;
while((readBytes = buf.read()) != -1)
stream.write(readBytes);
System.out.println("Response Stream"+stream);
} catch (IOException ioe){
throw new ServletException(ioe.getMessage());
} finally {
if(stream != null)
stream.close();
if(buf != null)
buf.close();
}
}
}
if (filePath == null || filePath.equals(""))
throw new ServletException(
"Invalid or non-existent mp3Dir context-param.");
URL url = null;
try{
url = f.toURL();
System.out.println("URL : "+ url);
System.out.println("Converting process Successfully");
}
catch (MalformedURLException me){
System.out.println("Converting process error");
}
//String rfilepath=this.getServletContext().getRealPath("/")+" AudioFileStorage/test.mp3";
//System.out.println("Path of the rfilepath " + rfilepath);
}
}
here can i get that audiorecordtest.mp3 file directly from client without decoding in server side and play it in this servlet
my server connection in local for client
executepost() is as follows:
package com.android.audio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class AudioServer {
static InputStream is;
private static String API_URL = "http://192.168.15.71:8088/QRBarCodeServer/";
public static String executePost(String apiurl,
ArrayList<NameValuePair> urlParameters) {
try {
// Create connection
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(API_URL + apiurl);
httppost.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
// Get Response
// InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response1 = new StringBuffer();
while ((line = rd.readLine()) != null) {
response1.append(line);
response1.append('\r');
}
rd.close();
return response1.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String executeHttpGet(String apiurl) throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(API_URL + apiurl);
request.setURI(new URI(apiurl));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
here is simple way to do that
1: from android side read that .mp3 file and create base64String from it.
2: At servier side read this base64String and convert it back to .mp3 file.
to convert any file to base64String following is the process
File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
You can reach it using apache MultipartEntity:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(BASE_URL);
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("Audiofile", new FileBody(file, "audio/mpeg"));
post.setEntity(mpEntity);
HttpResponse res = client.execute(post);
Yea you can send this in Servlet there is Mime type mime means multimedia extension
I am sending code i can guarantee that it will work in Servlet in java and you should take
care for android by own
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendMp3Envious extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileName = (String) request.getParameter("file");
if (fileName == null || fileName.equals(""))
throw new ServletException(
"Invalid or non-existent file parameter in SendMp3 servlet.");
if (fileName.indexOf(".mp3") == -1)
fileName = fileName + ".mp3";
String mp3Dir = getServletContext().getInitParameter("mp3-dir");
if (mp3Dir == null || mp3Dir.equals(""))
throw new ServletException(
"Invalid or non-existent mp3Dir context-param.");
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
stream = response.getOutputStream();
File mp3 = new File(mp3Dir + "/" + fileName);
//set response headers
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition", "attachment; filename="
+ fileName);
response.setContentLength((int) mp3.length());
FileInputStream input = new FileInputStream(mp3);
buf = new BufferedInputStream(input);
int readBytes = 0;
//read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} finally {
if (stream != null)
stream.close();
if (buf != null)
buf.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Categories

Resources