MultipartEntityBuilder to send data from Android httpurlconnection - android

i am trying to change HTTPClient deprecated code but i get error on setEntity because its dapricated and i dont know how to paas MultipartEntityBuilder by new httpConnectionUrl.
my old deprecated code snippt
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(imagePostUrl);
for (String fileName : fileNameArrayList) {
File file = new File(fileName);
// 1st
int quality = GeneralUtil.getQualityOfImage(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (quality <= 25) { // This means image file size is in MB's so we need to avoide out of memory issues.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
try {
bitmap = BitmapFactory.decodeFile(file.getPath(), options);
} catch (OutOfMemoryError E) {
System.gc();
bitmap = GeneralUtil.decodeFile(file);
}
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} else {
try {
bitmap = BitmapFactory.decodeFile(file.getPath());
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError E) {
System.gc();
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
bitmap = BitmapFactory.decodeFile(file.getPath(), options);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError ex) {
bitmap = GeneralUtil.decodeFile(file);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
throw new Exception();
}
}
}
byte[] data = bos.toByteArray();
String timeStamp = GeneralUtil.generateTimeStamp();
ByteArrayBody bin = new ByteArrayBody(data, myMobileNo + "_" + userName + "_" + timeStamp + ".jpg");
MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
multiPartEntityBuilder.addPart("uploadedfile1", bin);
multiPartEntityBuilder.addPart("inviteId", new StringBody(inviteIdArrayList.get(0).toString(), Charset.forName("UTF-8")));
post.setEntity(multiPartEntityBuilder.build());
HttpResponse httpResponse = null;
httpResponse = client.execute(post);
InputStream inputStream = null;
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result.add(convertInputStreamToString(inputStream));
else
result.add("Did not work!");
}
my new not working code snippt
try {
HttpURLConnection httpcon = (HttpURLConnection) ((new URL(imagePostUrl).openConnection()));
httpcon.setDoOutput(true);
for (String fileName : fileNameArrayList) {
File file = new File(fileName);
int quality = GeneralUtil.getQualityOfImage(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (quality <= 25) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
try {
bitmap = BitmapFactory.decodeFile(file.getPath(), options);
} catch (OutOfMemoryError E) {
System.gc();
bitmap = GeneralUtil.decodeFile(file);
}
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} else {
try {
bitmap = BitmapFactory.decodeFile(file.getPath());
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError E) {
System.gc();
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
bitmap = BitmapFactory.decodeFile(file.getPath(), options);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
} catch (OutOfMemoryError ex) {
bitmap = GeneralUtil.decodeFile(file);
bitmap.compress(CompressFormat.JPEG, quality, bos);
bitmap.recycle();
bitmap = null;
throw new Exception();
}
}
}
byte[] data = bos.toByteArray();
String timeStamp = GeneralUtil.generateTimeStamp();
ByteArrayBody bin = new ByteArrayBody(data, myMobileNo + "_" + userName + "_" + timeStamp + ".jpg");
MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
multiPartEntityBuilder.addPart("uploadedfile1", bin);
multiPartEntityBuilder.addPart("inviteId", new StringBody(inviteIdArrayList.get(0).toString(), Charset.forName("UTF-8")));
httpcon.setEntity(multiPartEntityBuilder.build()); **error**
// Execute POST request to the given URL
// HttpResponse httpResponse = null;
// httpResponse = client.execute(post);
httpcon.setRequestMethod("POST");
httpcon.connect();

Here is my suggested alternative solution:
First of all, you can refer to some of the following libraries: Volley, Retrofit...
If you want to use Volley, you can refer to some following links:
Working POST Multipart Request with Volley and without HttpEntity
How to send a “multipart/form-data” POST in Android with Volley
My sample code relating to the first link above
MultipartActivity.java:
public class MultipartActivity extends Activity {
private final Context context = this;
private final String twoHyphens = "--";
private final String lineEnd = "\r\n";
private final String boundary = "apiclient-" + System.currentTimeMillis();
private final String mimeType = "multipart/form-data;boundary=" + boundary;
private byte[] multipartBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multipart);
byte[] fileData1 = getFileDataFromDrawable(context, R.drawable.ic_action_android);
byte[] fileData2 = getFileDataFromDrawable(context, R.drawable.ic_action_book);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
// the first file
buildPart(dos, fileData1, "ic_action_android.png");
// the second file
buildPart(dos, fileData2, "ic_action_book.png");
// send multipart form data necesssary after file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// pass to multipart body
multipartBody = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
String url = "http://192.168.1.100/api/postfile";
MultipartRequest multipartRequest = new MultipartRequest(url, null, mimeType, multipartBody, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
Toast.makeText(context, "Upload successfully!", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Upload failed!\r\n" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
VolleySingleton.getInstance(context).addToRequestQueue(multipartRequest);
}
...
private void buildPart(DataOutputStream dataOutputStream, byte[] fileData, String fileName) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""
+ fileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
ByteArrayInputStream fileInputStream = new ByteArrayInputStream(fileData);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024 * 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);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
}
private byte[] getFileDataFromDrawable(Context context, int id) {
Drawable drawable = ContextCompat.getDrawable(context, id);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
}
MultipartRequest.java:
class MultipartRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
private final Map<String, String> mHeaders;
private final String mMimeType;
private final byte[] mMultipartBody;
public MultipartRequest(String url, Map<String, String> headers, String mimeType, byte[] multipartBody, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
this.mHeaders = headers;
this.mMimeType = mimeType;
this.mMultipartBody = multipartBody;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
#Override
public String getBodyContentType() {
return mMimeType;
}
#Override
public byte[] getBody() throws AuthFailureError {
return mMultipartBody;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
Of course, you can find more available in SO.
Hope this helps!

I was able to get my Multipart Form Data upload thing to work after a lot of head scratching and hair pulling.
Below class is used for multipart file uploading and it works.
NB: This is not a question, merely an answer to the op.
public class WebConnector {
String boundary = "-------------" + System.currentTimeMillis();
private static final String LINE_FEED = "\r\n";
private static final String TWO_HYPHENS = "--";
private StringBuilder url;
private String protocol;
private HashMap<String, String> params;
private JSONObject postData;
private List<String> fileList;
private int count = 0;
private DataOutputStream dos;
public WebConnector(StringBuilder url, String protocol,
HashMap<String, String> params, JSONObject postData) {
super();
this.url = url;
this.protocol = protocol;
this.params = params;
this.postData = postData;
createServiceUrl();
}
public WebConnector(StringBuilder url, String protocol,
HashMap<String, String> params, JSONObject postData, List<String> fileList) {
super();
this.url = url;
this.protocol = protocol;
this.params = params;
this.postData = postData;
this.fileList = fileList;
createServiceUrl();
}
public String connectToMULTIPART_POST_service(String postName) {
System.out.println(">>>>>>>>>url : " + url);
StringBuilder stringBuilder = new StringBuilder();
String strResponse = "";
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url.toString()).openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
urlConnection.setRequestProperty("Authorization", "Bearer " + Config.getConfigInstance().getAccessToken());
urlConnection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + boundary);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setChunkedStreamingMode(1024);
urlConnection.setRequestMethod("POST");
dos = new DataOutputStream(urlConnection.getOutputStream());
Iterator<String> keys = postData.keys();
while (keys.hasNext()) {
try {
String id = String.valueOf(keys.next());
addFormField(id, "" + postData.get(id));
System.out.println(id + " : " + postData.get(id));
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
dos.writeBytes(LINE_FEED);
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fileList != null && fileList.size() > 0 && !fileList.isEmpty()) {
for (int i = 0; i < fileList.size(); i++) {
File file = new File(fileList.get(i));
if (file != null) ;
addFilePart("photos[" + i + "][image]", file);
}
}
// forming th java.net.URL object
build();
urlConnection.connect();
int statusCode = 0;
try {
urlConnection.connect();
statusCode = urlConnection.getResponseCode();
} catch (EOFException e1) {
if (count < 5) {
urlConnection.disconnect();
count++;
String temp = connectToMULTIPART_POST_service(postName);
if (temp != null && !temp.equals("")) {
return temp;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// 200 represents HTTP OK
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
strResponse = readStream(inputStream);
} else {
System.out.println(urlConnection.getResponseMessage());
inputStream = new BufferedInputStream(urlConnection.getInputStream());
strResponse = readStream(inputStream);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != inputStream)
inputStream.close();
} catch (IOException e) {
}
}
return strResponse;
}
public void addFormField(String fieldName, String value) {
try {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"" + LINE_FEED + LINE_FEED/*+ value + LINE_FEED*/);
/*dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + LINE_FEED);*/
dos.writeBytes(value + LINE_FEED);
} catch (IOException e) {
e.printStackTrace();
}
}
public void addFilePart(String fieldName, File uploadFile) {
try {
dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + uploadFile.getName() + "\"" + LINE_FEED);
dos.writeBytes(LINE_FEED);
FileInputStream fStream = new FileInputStream(uploadFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
dos.write(buffer, 0, length);
}
dos.writeBytes(LINE_FEED);
dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS + LINE_FEED);
/* close streams */
fStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void addHeaderField(String name, String value) {
try {
dos.writeBytes(name + ": " + value + LINE_FEED);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build() {
try {
dos.writeBytes(LINE_FEED);
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String readStream(InputStream in) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String nextLine = "";
while ((nextLine = reader.readLine()) != null) {
sb.append(nextLine);
}
/* Close Stream */
if (null != in) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
private void createServiceUrl() {
if (null == params) {
return;
}
final Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
boolean isParam = false;
while (it.hasNext()) {
final Map.Entry<String, String> mapEnt = (Map.Entry<String, String>) it.next();
url.append(mapEnt.getKey());
url.append("=");
try {
url.append(URLEncoder.encode(mapEnt.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
url.append(WSConstants.AMPERSAND);
isParam = true;
}
if (isParam) {
url.deleteCharAt(url.length() - 1);
}
}
}

Related

Multipart HttpUrlConnection data not receiving

I am wondering here and there from last 2 days. My issue is that I am sending multiple files with some text/plain fields using multipart/form-data.
The issue is that when I am sending data using HTTPCLient its working fine but when I am trying to send data using HTTPURLConnection, server is not receiving anything, below is my MultipartUtility,
public class MultipartUtils extends NetworkUtility
{
private static final String END_REQUEST = "--";
private String mBoundary;
public MultipartUtils()
{
mBoundary = END_REQUEST + "quAxBSd";
}
public HttpURLConnection getUrlConnection(String URL, String httpMethod,
String contenttype, String boundry) throws Exception
{
URL url = new URL(URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (httpMethod.equalsIgnoreCase(HTTP_GET) == false)
urlConnection.setDoInput(true);
else
urlConnection.setDoInput(false);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod(httpMethod);
if (contenttype.equalsIgnoreCase(APPLICATION_MULTIPART))
{
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundry);
urlConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
}
else
{
urlConnection.setRequestProperty("Content-Type", contenttype);
}
return urlConnection;
}
public String uploadImagesAddPost(Activity mContext, String URL, String jsonString, ArrayList<ImageListBean> mImageBeanList) throws Exception
{
HttpURLConnection httpURLConnection = getUrlConnection(URL, HTTP_POST, APPLICATION_MULTIPART, mBoundary);
httpURLConnection.connect();
DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
PrintWriter writer = new PrintWriter(new OutputStreamWriter(dataOutputStream, UTF8),
true);
addJsonToPart(writer, jsonString);
for (int i = 0; i < mImageBeanList.size(); i++)
{
try
{
byte[] imageByteArray = {};
Uri imageUri = mImageBeanList.get(i).getmUri();
String imagePath = ImageCaputureUtility.getPath(imageUri, mContext);
if (!imagePath.equals(""))
{
if (mImageBeanList.get(i).getmType().equalsIgnoreCase(MellTooConstants.IMG))
{
//For img
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, outputStream);
imageByteArray = outputStream.toByteArray();
addFileAsByte(dataOutputStream, "imageview" + (i + 1), imageByteArray, ("imageview" + (i + 1)) + ".jpeg", IMAGE_JPEG);
}
else
{
//For video
/* Uploading thumb*/
Bitmap bitmap = UtilsMellToo.createThumb(imageUri, mContext);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, outputStream);
imageByteArray = outputStream.toByteArray();
addFileAsByte(dataOutputStream, "imageview4", imageByteArray, "imageview4" + ".jpeg", IMAGE_JPEG);
/* Uploading video*/
imageByteArray = MellTooUtil.readFileToByteArray(new File(imagePath));
addFileAsByte(dataOutputStream, "video", imageByteArray, "video" + (i + 1) + ".mp4", VIDEO_MP4);
}
}
else
{
//No need to upload data
}
}
catch (Exception e)
{
e.printStackTrace();
}
if (i + 1 != mImageBeanList.size())
writer.append(mBoundary).append(CHANGE_LINE);
}
writer.append(mBoundary + END_REQUEST);
writer.flush();
return getResponse(httpURLConnection);
}
private void addJsonToPart(PrintWriter writer, String text)
{
writer.append(mBoundary).append(CHANGE_LINE);
writer.append(CONTENT_DISPOSITION + FORM_DATA + NAME + "\"formstring\"").append(CHANGE_LINE);
writer.append(CONTENT_TYPE + PLAIN_TEXT + CHARSET + UTF8).append(CHANGE_LINE);
writer.append(CONTENT_TRANSFER_ENCODING + "8bit").append(CHANGE_LINE);
writer.append(text).append(CHANGE_LINE);
writer.flush();
}
public void addFileAsByte(DataOutputStream outputStream, String fieldName, byte[] imageByteArray, String fileName, String contentType) throws IOException
{
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, UTF8),
true);
writer.append(mBoundary).append(CHANGE_LINE);
writer.append(CONTENT_DISPOSITION + FORM_DATA + NAME + "\"" + fieldName + "\";" + FILE_NAME + "\"" + fileName + "\"").append(CHANGE_LINE);
writer.append(CONTENT_TYPE + contentType).append(CHANGE_LINE);
writer.append(CONTENT_TRANSFER_ENCODING + BINARY).append(CHANGE_LINE);
writer.flush();
InputStream inputStream = new ByteArrayInputStream(imageByteArray);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.writeBytes(CHANGE_LINE);
outputStream.flush();
inputStream.close();
}
}
Below is the method, how I am using this class,
jsonResponseString = new MultipartUtils()
.uploadImagesAddPost(mContext, AppConstants.BASE_URL + AppConstants.SAVE_POST_URL,
mJsonString, mImageList);
Below is my ASP side,
HttpContextWrapper.Request.Form["formstring"]; //This is returning null
Please help me out from this...!!!
Thanks in advance
Below is my request,
After struggling approximately 4 days, I found the issue was in the boundry and the new line in the request....!
There should be a boundary and a blank line between text and image part and I was not using it. The blank line is separating the header from the boday of the each part of a multipart/form-data request...!

How to upload image from gallary to server?

I am trying to browse image from my gallery and trying to send it in server and following this tutorial http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106 using json but whenever I am trying to upload it shows file uploaded successfull,but when i click on browse button my gallary display nothing,so i need to first browse from gallery and show that image in my imageview and then upload successfullcan any body tell me what is problem?
UploadToServer :
public class UploadToServer extends Activity {
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/Pictures/";
final String uploadFileName = "service_lifecycle.png";
private static int RESULT_LOAD_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
ImageView buttonLoadImage = (ImageView) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
messageText.setText("Uploading file path :- '/mnt/sdcard/Pictures/"+uploadFileName);
/************* Php script path ****************/
upLoadServerUri = "http://www.androidexample.com/media/UploadToServer.php";
uploadButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
uploadFile(uploadFilePath + "" + uploadFileName);
}
}).start();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, this);
//add this
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(tempPath ));
}
}
private String getPath(Uri uri, UploadToServer uploadToServer) {
if( uri == null ) {
return null;
}
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+uploadFilePath + "" + uploadFileName);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
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("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_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)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" http://www.androidexample.com/media/uploads/"
+uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
You should try updating your uploadFilePath variable. Get the top level external storage directory first by using Environment.getExternalStoragePublicDirectory() and then suffix the relative path to your image to access the file for uploading. Here is the documentation: http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)
You can use multipart image upload like this.
create AsyncTask
ArrayList productFiles = new ArrayList();
class UploadImageTask extends AsyncTask<String, Integer, String>
{
ProgressDialog dialog;
#Override
protected String doInBackground(String... params)
{
int isCover = 0;
String gal_image = "";
for (int i = 0; i < productFiles.size(); i++)
{
if (i == 0)
isCover = 1;
else
isCover = 0;
publishProgress(i + 1);
String s = HelperHttp.uploadFile(productFiles.get(i),
Constants.BASE_URL + "send_image.php", params[0],
isCover + "");
try {
JSONObject job = new JSONObject(s);
if (job.optInt("status") == 1) {
Helper.Log("Upload success", i + " done");
if (gal_image.equals(""))
gal_image = job.optString("gal_image");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return gal_image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = DialogManager.getProgressDialog(SellActivity.this);
dialog.setMessage("uploading 1 of " + productFiles.size()+ " image(s)");
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
dialog.dismiss();
}
}
2.
Create Helper class with method upload file as follow
public static String uploadFile(File file, String url, String productId,String isCover)
{
StringBuffer data = new StringBuffer();
HttpPost httpost = new HttpPost(url);
Helper.Log("Upload file", url);
MultipartEntity entity = new MultipartEntity();
entity.addPart("uploadfile", new FileBody(file));
try
{
entity.addPart("txtProductId", new StringBody(productId));
}
catch (UnsupportedEncodingException e1)
{
e1.printStackTrace();
}
httpost.setEntity(entity);
HttpResponse response;
try {
response = getThreadSafeClient().execute(httpost);
HttpEntity entity2 = response.getEntity();
InputStream is = entity2.getContent();
BufferedReader reader = new BufferedReader( new InputStreamReader(is), 8192);
String line = null;
while ((line = reader.readLine()) != null)
{
data.append(line);
}
response.getEntity().consumeContent();
Helper.Log("Response==>", data.toString() + "");
return data.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
You can also add parameter to request.
To add parameter use following code
entity.addPart("Key", value);
Convert the image to bitmap
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
Send the encodedImage to server as string, decode it at the server level to get the string

Android send image to webserver

I have this task to send a picture i take with my app to a webserver. this is my camera activity where i would like to send the image in the onActivityResult method. I have trouble finding up to date solutions to this as all i can find seems to be using MultipartEntity which is now deprecated.
package com.ndjk;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;
public class CameraActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
public ImageView imageView;
public static final String URI_PATH = "Uri";
Uri imageUri = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frontpage);
imageView = (ImageView) findViewById(R.id.pictureImageView);
open();
}
public void open() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(bp);
Intent frontPageIntent = new Intent(this, FrontPageActivity.class);
imageUri = data.getData();
frontPageIntent.putExtra(URI_PATH, imageUri.toString());
frontPageIntent.putExtra("MapPhoto", bp);
startActivity(frontPageIntent);
}
}
As an alternative, I would highly recommend using Retrofit a REST library from Square. Retrofit
You would create a Java interface like this:
#Multipart
#POST("/webservice/{userid}/avatar.json")
Object uploadImage(
#Header("Rest-User-Token") String token,
#Path("userid") String userId,
#Part("FileData") TypedFile pictureFile
);
Then it is just a case of converting the Intent data to a File object, and than creating a TypedFile as follows:
TypedFile in = new TypedFile("image/jpeg", imageFile);
I think the answer is here:
https://stackoverflow.com/a/19196621/1652236
You should use MultipartEntityBuilder as an alternative
Edit - 1
You can open camera with this code:
private static final int RESULT_TAKE_PHOTO = 1;
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, RESULT_TAKE_PHOTO);
Your onActivityResult must be like this :
if (resultCode == RESULT_OK) {
File file = null;
String filePath = null;
try {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
rotateDegree = getCameraPhotoOrientation(getApplicationContext(), selectedImage, picturePath);
bmp = BitmapFactory.decodeFile(picturePath);
bmp = rotateImage(bmp, rotateDegree);
file = new File(filePath);
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
fOut.flush();
fOut.close();
resultCode=0;
} catch (Exception e) {
e.printStackTrace();
}
}
So if take the picture You can use this AsyncTask for sending. You can show a progress bar while sending file to server. It's working for me.
public class SendFile extends AsyncTask<String, Integer, Integer> {
private Context conT;
private ProgressDialog dialog;
private String SendUrl = "";
private String SendFile = "";
private String Parameters = "";
private String result;
public File file;
SendFile(Context activity, String url, String filePath, String values) {
conT = activity;
dialog = new ProgressDialog(conT);
SendUrl = url;
SendFile = filePath;
Parameters = Values;
}
#Override
protected void onPreExecute() {
file = new File(SendFile);
dialog.setMessage("Please Wait..");
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax((int) file.length());
dialog.show();
}
#Override
protected Integer doInBackground(String... params) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****"
+ Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 512;
String[] q = SendFile.split("/");
int idx = q.length - 1;
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(SendUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent",
"Android Multipart HTTP Client 1.0");
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=dosya; filename=\""
+ q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpg" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
int boyut = 0;
while (bytesRead > 0) {
boyut += bytesRead;
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
dialog.setProgress(boyut);
}
outputStream.writeBytes(lineEnd);
String[] posts = Bilgiler.split("&");
int max = posts.length;
for (int i = 0; i < max; i++) {
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String[] kv = posts[i].split("=");
outputStream
.writeBytes("Content-Disposition: form-data; name=\""
+ kv[0] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain"
+ lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(kv[1]);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
Log.v("TAG","result:"+result);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(Integer result1) {
dialog.dismiss();
};
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
and if you are sending to PHP server, this code will help you.
<?php
$file_path = "test/";
$username= $_POST["username"];
$password= $_POST["password"];
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
Edit - 2:
you can call this AsyncTask like :
String FormData = "username=" + Session.getUsername()
+ "&password=" + Session.getPassword() ;
SendFile SendIt= new SendFile(this, upLoadServerUri, filePath,FormData);
SendIt.execute();

Unable to upload pictures to the server in the same application that captured them

Initially on clicking the camera button the image is being captured, displays the save and discard buttons. On clicking save it gets saved in the the specified folder, but the saved image is not being uploaded into the server.
Here is my code:
public class FldrActivity extends Activity {
private static final int CAPTURE_IMAGE = 0;
InputStream inputStream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File folder = new File(Environment.getExternalStorageDirectory() + "/image");
boolean success = false;
if (!folder.exists()) {
success = folder.mkdir();
}
String path = folder + "/example.jpg";
//String path = Environment.getExternalStorageDirectory() + "/image/example2.jpg";
File file = new File(path);
Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult( intent, CAPTURE_IMAGE );
String pathToOurFile = "/sdcard/image/example.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(pathToOurFile);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
//compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeToString(byte_arr, 0);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("file",image_str));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.xyz.com/image/connection.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String the_string_response = convertResponseToString(response);
Toast.makeText(getApplicationContext(), "Response " + the_string_response,
Toast.LENGTH_LONG).show();
} catch(Exception {
Toast.makeText(getApplicationContext(), "ERROR " + e.getMessage(),
Toast.LENGTH_LONG).show();
System.out.println("Error in http connection "+e.toString());
}
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException {
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
Toast.makeText(getApplicationContext(), "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0) {
}
else {
byte[] data = new byte[512];
int len = 0;
try {
while (-1 != (len = inputStream.read(data)) ) {
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close(); // closing the stream…..
} catch (IOException e) {
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
Toast.makeText(getApplicationContext(), "Result : " + res, Toast.LENGTH_LONG).show();
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
}
return res;
}
}

how to Upload image into server in Android?

I am trying to Upload image Capture by Camera into server. server send response code = 200 but Image is not upload into server.
Code is :
private boolean uploadData() {
int count = this.forumThreadsB.size();
for (int i = 0; i < count; i++)
{
if (isPhoto)
message = "Uploading Shared Items " + (i + 1) + " of " + count;
else
message = "Uploading Shared Items " + (i + 1) + " of " + count;
progressCount = (i * 1000)/count;
Hashtable<?, ?> threadD = (Hashtable<?, ?>)this.forumThreadsB.elementAt(i);
String onlinePath = "http://xyx.com/;
threadid = (String) threadD.get("devicethreadid");
Hashtable<String, String> pairs = new Hashtable<String, String>();
pairs.put("forumid", threadD.get("lmsforumid").toString());
pairs.put("topicid", threadD.get("lmsthreadid").toString());
pairs.put("clientid", LoginHelper.clientid);
String fullfilepath = threadD.get("offlinepath").toString();
int index = threadD.get("offlinepath").toString().lastIndexOf("/");
String filename = fullfilepath.substring(index + 1);
String filetype = "";
if (filename.toLowerCase().contains(".png"))
filetype = "image/png";
else if (filename.toLowerCase().contains(".jpg"))
filetype = "image/jpeg";
else if (filename.toLowerCase().contains(".mp4"))
filetype = "image/mp4";
else if (filename.toLowerCase().contains(".3gp"))
filetype = "image/3gpp";
String boundaryMessage = getBoundaryMessage(BOUNDARY, pairs, fullfilepath, filename, filetype);
String endBoundary = "\r\n--" + BOUNDARY + "--\r\n";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
URL url = new URL(onlinePath);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDARY);
dos = new DataOutputStream( conn.getOutputStream() );
dos.write( boundaryMessage.getBytes());
File file = new File(fullfilepath.substring(6));
FileInputStream fileInputStream = new FileInputStream(file);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
}
dos.write(endBoundary.getBytes());
dos.flush();
dos.close();
fileInputStream.close();
} catch (IOException ioe) {
Log.e("SyncUploadDownloadHelper", "Cannot upload file: " + ioe.getMessage(), ioe);
//return false;
}
// Read response
try {
int responseCode = conn.getResponseCode();
if(responseCode == 200){
SQLiteForumDAO forumDAO = new SQLiteForumDAO(mcontext) ;
ForumThreadDTO forumThreadDTO = forumDAO.selectThread(this.threadid);
if(downloadPath!=null && downloadPath.equalsIgnoreCase("null") && downloadPath.equalsIgnoreCase(""))
forumThreadDTO.offlinefilepath = downloadPath;
forumDAO.updateThread(forumThreadDTO);
}
} catch (IOException ioex) {
Log.e("SyncUploadDownloadHelper", "Upload file failed: " + ioex.getMessage(), ioex);
//return false;
} catch (Exception e) {
Log.e("SyncUploadDownloadHelper", "Upload file failed: " + e.getMessage(), e);
//return false;
}
if (i == (this.forumThreadsB.size() - 1)){
this.sendStatus = "true";
progressCount = 1000;
SyncUploadDownloadHelper.this.notifyObservers("SyncUploadDownloadHelper:UploadDataFinish");
}
else
SyncUploadDownloadHelper.this.notifyObservers("SyncUploadDownloadHelper:UploadData");
//return true;
}
return true;
}
Function :
private String getBoundaryMessage(String boundary, Hashtable<String, String> params, String fileField, String fileName, String fileType) {
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
Enumeration<String> keys = params.keys();
while(keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = (String)params.get(key);
System.out.println(key + ": " + value);
res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")
.append("\r\n").append(value).append("\r\n").append("--").append(boundary).append("\r\n");
}
res.append("Content-Disposition: form-data; name=\"").append("file").append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(fileType).append("\r\n\r\n");
return res.toString();
}
in my Application I Capture Image and Save it to Database. path of save image is use to upload image file.
I using this:
public class HttpClient extends AsyncTask<Void, Integer, Long> {
private static final int PROGRESS_DIALOG = 0;
public ProgressDialog dialog;
public File file;
protected Long doInBackground(Void... params) {
for (File file : files) {
foto = "/sdcard/CameraExample/" + file.getName();
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urll);
MultipartEntity mpEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("form_file", new FileBody(file, "image/jpeg"));
httppost.setEntity(mpEntity);
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
}
if (resEntity != null) {
resEntity.consumeContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(Long unused) {
progressDialog.dismiss();
((Runnable) ctx ).run();
super.onPostExecute(unused);
}
protected void onPreExecute() {
progressDialog = new ProgressDialog(ctx);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Загрузка фото...");
progressDialog.setProgress(0);
progressDialog.setMax(count);
progressDialog.show();
}
}
This code using that library:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.james.mime4j.message.Message;
You can find this in Google. If you don't find - i can send you this libraries.

Categories

Resources