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.
Related
I am trying to upload image over android device , i have tried uploading image from most of the devices and image is been uploaded from sdcard as well as DCIM folder , my issues persist in only samsung devices as of now and it is very specific to DCIM folder images only , if i try upload image from other folder in sdcard that works.
Any pointers would be great , below is code snippet :
public class UploadImageService extends Service {
private static final String TAG = UploadImageService.class.getSimpleName();
private int mServerResponseCode = 0;
private String upLoadServerUri = null;
private Boolean mUsSuccess = true;
private String mUploadImagePaths = "";
private static RotiSharedPreferance sharedPref;
#Override
public void onCreate() {
Log.d(TAG, "Service onCreate");
sharedPref = new RotiSharedPreferance(RotiApplication.getInstance());
// upLoadServerUri = "http://mymasterpeice.byethost15.com/mobile/D21/upload_image.php";
upLoadServerUri = Constants.ROTI_HOST_NAME + Constants.ROTI_IMAGE_UPLOAD_API;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service onStartCommand " + startId);
final int currentId = startId;
Runnable r = new Runnable() {
public void run() {
File[] files = getFiles();
for (int i = 0; i < files.length; i++) {
synchronized (this) {
try {
Log.d("MyService", "run (line 62): uploadFile " + files[i].getAbsolutePath());
uploadFile(files[i].getAbsolutePath());
} catch (Exception e) {
mUsSuccess = false;
}
}
Log.d(TAG, "Service running " + currentId);
}
stopSelf();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(Constants.UPDATE_UI_IMAGE_UPLOAD_ACK_BROADCAST);
broadcastIntent.putExtra(Constants.UPDATE_UI_IMAGE_UPLOAD_ACK_BROADCAST_PARAM, mUploadImagePaths);
sendBroadcast(broadcastIntent);
}
};
Thread t = new Thread(r);
t.start();
return Service.START_STICKY;
}
public static File[] getFiles() {
File mFile = null;
File[] mListFile = null;
try {
// Locate the image folder in your SD Card
mFile = new File(sharedPref.getString(Constants.UPLOAD_IMAGE_SHARED_PREF));
mListFile = new File[1];
mListFile[0] = mFile;
} catch (NullPointerException e) {
e.printStackTrace();
}
return mListFile;
}
#Override
public IBinder onBind(Intent arg0) {
Log.d(TAG, "Service onBind");
return null;
}
/**
* #inheritDoc
*/
#Override
public void onDestroy() {
Log.d(TAG, "Service onDestroy");
}
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(fileName);
if (!sourceFile.isFile()) {
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("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ sharedPref.getString(Constants.UPLOAD_IMAGE_NAME_SHARED_PREF) + "\"" + 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)
mServerResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
StringBuilder result = new StringBuilder();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}
Log.d("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + mServerResponseCode);
Log.d("uploadFile", "HTTP Response is : " + result);
JSONObject object = new JSONObject(String.valueOf(result));
String filePath = (String) object.get("file_path");
Log.d(TAG, "filepath : " + filePath);
mUploadImagePaths = (filePath);
if (mServerResponseCode != 200) {
mUsSuccess = false;
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
mUsSuccess = false;
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
mUploadImagePaths = "";
} catch (Exception e) {
mUsSuccess = false;
e.printStackTrace();
Log.e(TAG, "Exception : " + e.getMessage(), e);
mUploadImagePaths = ("");
}
return mServerResponseCode;
} // End else block
}
}
I develop one app. In my app i take one image from camera or one from gallery. I want to post image to server using Multipart but image not post it. My post data is below
{
"suggested_item" :{
"name": "apple",
"description" : "nice apple",
"image": "image.png"
}
}
My java code is
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_FROM_CAMERA) {
try{
if(resultCode == -1){
File file = new File(Environment.getExternalStorageDirectory()+File.separator +"image.png");
bitmap = loadBitmap(file);
iv_pic.setImageBitmap(bitmap);
try {
Uri tempUri = getImageUri(getActivity(), bitmap);
Log.i(TAG,"onActivityResult PICK_FROM_CAMERA, tempUri : "+tempUri);
//uploadFile(tempUri + "" + System.currentTimeMillis()+".png");
} catch (Exception e) {
e.printStackTrace();
}
}else{
//setResult(RESULT_CANCELED);
//Activity.this.finish();
}
}catch(Exception e){
e.printStackTrace();
}
}else if (requestCode == PICK_FROM_GALLERY) {
try{
//Log.i(TAG,"onActivityResult PICK_FROM_GALLERY, data : "+data);
if(data !=null){
bitmap = null;
try {
bitmap = new BitmapDrawable(MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData())).getBitmap();
iv_pic.setImageBitmap(bitmap);
try {
Uri tempUri = getImageUri(getActivity(), bitmap);
Log.i(TAG,"onActivityResult PICK_FROM_GALLERY, tempUri : "+tempUri);
//uploadFile(tempUri + "" + System.currentTimeMillis()+".png");
} catch (Exception e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
//setResult(RESULT_CANCELED);
//Activity.this.finish();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public Uri getImageUri(Context context , Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG , 100 , bytes);
String path = Images.Media.insertImage(context.getContentResolver() , bitmap , "Title" , null);
return Uri.parse(path);
}
please help me thanks in advance.
To send binary data you need to use addBinaryBody method of MultipartEntityBuilder. Sample of attaching:
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
//Image attaching
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
File file;
multipartEntity.addBinaryBody("someName", file, ContentType.create("image/jpeg"), file.getName());
//Json string attaching
String json;
multipartEntity.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN));
Then make request as usual:
HttpPut put = new HttpPut("url");
put.setEntity(multipartEntity.build());
HttpResponse response = client.execute(put);
int statusCode = response.getStatusLine().getStatusCode();
I suggest using retrofit.
Posting multipart will be something like this:
#Multipart
#PUT("user/photo")
Call<User> updateUser(#Part("photo") RequestBody photo, #Part("description") RequestBody description);
Refer to this question for more details.
This is a good tutorial to check if you are not familiar to retrofit.
Here I am Posting Full Code for Upload Image Using HTTP on Server also PHP code for understanding,
Class File
package com.stackexmples;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by windws on 26-Mar-16.
*/
public class UploadImage extends AppCompatActivity implements View.OnClickListener {
private static final int REQUEST_TAKE_GALLERY_VIDEO = 11;
private static final String TAG = "UploadMultipleFile";
private AppCompatButton btnUploadFiles;
private AppCompatButton bntSelectImage;
private String filemanagerstring;
private String selectedImagePath="";
private TextView tvVideoList;
private TextView tvImageList;
private int selected = 0;
private LinearLayout ll;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_multiple_file);
initView();
initListener();
}
private void initView() {
btnUploadFiles = (AppCompatButton) findViewById(R.id.btnUploadFiles);
bntSelectImage = (AppCompatButton) findViewById(R.id.bntSelectImage);
}
private void initListener() {
btnUploadFiles.setOnClickListener(this);
bntSelectImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == btnUploadFiles) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
uploadFile("Data you want to sent");
}
});
thread.start();
} else if (v == bntSelectImage) {
selectImage();
}
}
private void selectImage() {
selected = 1;
Intent intent = new Intent();
intent.setType("Image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_TAKE_GALLERY_VIDEO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
Log.d(TAG, "Called-->onActivityResultCalled");
Uri selectedImageUri = data.getData();
Log.d(TAG, "selectedImageUri-->" + selectedImageUri);
selectedImagePath = selectedImageUri.toString().replace("file://", "");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public String uploadFile(String req) {
// TODO Auto-generated method stub
String serverResponseMessage = "";
String response_return = "";
Log.d("first str is:", req);
String urlString = "http://192.168.1.32/TestUpload/upload.php";
URL imageUrl = null;
try {
imageUrl = new URL(urlString); // get WebService_URL
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
// generating byte[] boundary here
HttpURLConnection conn = null;
DataOutputStream outputStream = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10 * 1024 * 1024;
try {
int serverResponseCode;
conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(conn.getOutputStream());
//////////////////////////////////////////////////////
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"json\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
outputStream.writeBytes("Content-Length: " + req.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(req + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
try {
FileInputStream fileInputStream = new FileInputStream(selectedImagePath);
String lastOne = "temp";
/////////////////////////////////////////////
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: attachment; name=\"imageKey" + "\";" + " filename=" + lastOne +".jpg" + lineEnd); // pass key & value of photo
/*outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd);*/
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // photo size bytes
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
Log.d("posttemplate", "connection outputstream size is " + outputStream.size());
fileInputStream.close();
} catch (OutOfMemoryError o) {
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
InputStream is = conn.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();
response_return = response1.toString();
Log.d("posttemplate", "server response code " + serverResponseCode);
Log.d("posttemplate", "server response message "
+ serverResponseMessage);
outputStream.flush();
outputStream.close();
conn.disconnect();
} catch (MalformedURLException e) {
Log.d("posttemplate", "malformed url", e);
} catch (IOException e) {
Log.d("posttemplate", "ioexception", e);
}
Log.d("response--->", "****" + response_return);
return response_return;
}
}
Layout File
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.materialexample.UploadMultipleFile.UploadMultipleFile">
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnUploadFiles"
android:text="Upload Files" />
<LinearLayout
android:id="#+id/linearLayout1"
android:orientation="vertical"
android:layout_below="#id/btnUploadFiles"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.AppCompatButton
android:id="#+id/bntSelectImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Image" />
</LinearLayout>
</RelativeLayout>
PHP Code For Understanding
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['imageKey']['name']);
if(move_uploaded_file($_FILES['imageKey']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
if(isset($_REQUEST['json'])){
echo "text is-->".$_REQUEST['json'];
}
?>
public class UploadProfilePicActivity extends Activity implements View.OnClickListener {
ImageView imageView;
Button btnUploadPic;
Button btnskipUploadPic;
Button btnSaveNContinue;
private static int RESULT_LOAD_IMAGE = 1;
String imagepath = null;
ProgressDialog dialog = null;
String url_profilePic;
private int serverResponseCode;
String api = "http://192.168.2.17:8000/api/v1/";
String format = "/?format=json";
AlmabayDatabase almabayDatabase;
String encodedString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadprofilepic);
imageView = (ImageView) findViewById(R.id.imageView);
btnUploadPic = (Button) findViewById(R.id.btnUploadPic);
btnskipUploadPic = (Button) findViewById(R.id.btnSkipUploadPic);
btnSaveNContinue = (Button) findViewById(R.id.btnSaveNContinue);
btnUploadPic.setOnClickListener(this);
btnSaveNContinue.setOnClickListener(this);
url_profilePic = api + "user-media" + format;
almabayDatabase = new AlmabayDatabase(this);
}
#Override
public void onClick(View v) {
if (v == btnUploadPic) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
} else if (v == btnSaveNContinue) {
dialog = ProgressDialog.show(UploadProfilePicActivity.this, "", "Uploading file...", true);
// messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
Log.e("ImagePathTest", imagepath);
uploadFile(imagepath);
}
}).start();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageView.setImageBitmap(bitmap);
Log.e("Uploading", "Uploading File :" + imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String imagepath) {
String fileName = imagepath;
Log.e("File Name", fileName);
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(fileName);
int pk = almabayDatabase.getUserID();
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + imagepath);
runOnUiThread(new Runnable() {
public void run() {
Log.e("Sourcefile", "File doesn't exist");
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(url_profilePic);
// 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("name", fileName);
// conn.setRequestProperty("timeline_id", String.valueOf(pk));
dos = new DataOutputStream(conn.getOutputStream());
//Send Image
Log.e("Sending","Sending Image");
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"name\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// add parameter timeline_id
String timeline_id = String.valueOf(pk);
Log.e("Sending","Sending PK");
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"timeline_id\"" + lineEnd);
dos.writeBytes(lineEnd);
// assign value
dos.writeBytes(timeline_id);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + 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();
Log.e("ResponseCode", String.valueOf(serverResponseCode));
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(UploadProfilePicActivity.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(UploadProfilePicActivity.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(UploadProfilePicActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file failed", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
In this code ,I am trying to send image to server alongwith timeline_id .timeline_id contains the value pk that is the primary key of the user stored in the database.I am not able to send image with timeline_id.I don't know where the actual problem is.Please help me to resolve the issue.
You can simple put the file part along with the text part using the class below.
String charset = "UTF-8";
String requestURL = BASE_URL + "userregistration";
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFormField("username", userJid);
multipart.addFilePart("image", imageBitmap);//ima
String response = multipart.finish();
Log.d("SERVER REPLIED", response);
You can create an MultipartUtility class as follow-
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* #param requestURL
* #param charset
* #throws IOException
*/
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("api_key", "a05f9ece-cd34-11e4-afdc-1681e6b88ec1");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
/**
* Adds a form field to the request
*
* #param name field name
* #param value field value
*/
public void addFormField(String name, String value) {
writer.append("--").
append(boundary).
append(LINE_FEED).
append("Content-Disposition: form-data; name=\"").
append(name).append("\"").
append(LINE_FEED).
append("Content-Type: text/plain; charset=").
append(charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
/**
* Adds a upload file section to the request
*
* #param fieldName name attribute in <input type="file" name="..." />
* #param fileBytes a File to be uploaded
* #throws IOException
*/
public void addFilePart(String fieldName, byte[] fileBytes)
throws IOException {
// String fileName = uploadFile.getName();
writer.append("--")
.append(boundary)
.append(LINE_FEED)
.append("Content-Disposition: form-data; name=\"")
.append(fieldName)
.append("\"; filename=\"")
.append("user.jpeg")
.append("\"")
.append(LINE_FEED)
.append("Content-Type: image/jpeg")
.append(LINE_FEED)
.append("Content-Transfer-Encoding: binary")
.append(LINE_FEED)
.append(LINE_FEED);
writer.flush();
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
/**
* Adds a header field to the request.
*
* #param name - name of the header field
* #param value - value of the header field
*/
public void addHeaderField(String name, String value) {
writer.append(name).append(": ").append(value).append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
*
* #return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* #throws IOException
*/
public String finish() throws IOException {
writer.append(LINE_FEED).flush();
writer.append("--")
.append(boundary)
.append("--")
.append(LINE_FEED)
.close();
String data = "";
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
data = data + line;
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return data.isEmpty() ? null : data;
}
}
I have fixed the issue.Just need to do the following changes in the uploadFile() method.Everything is working file now.
public int uploadFile(String imagepath) {
String fileName = imagepath;
Log.e("File Name", fileName);
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(fileName);
int pk = almabayDatabase.getUserID();
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + imagepath);
runOnUiThread(new Runnable() {
public void run() {
// messageText.setText("Source File not exist :"+ imagepath);
Log.e("Sourcefile", "File doesn't exist");
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(url_profilePic);
// 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("url", fileName);
// conn.setRequestProperty("timeline_id", String.valueOf(pk));
dos = new DataOutputStream(conn.getOutputStream());
// add parameter timeline_id
String timeline_id = String.valueOf(pk);
Log.e("Sending", "Sending PK");
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"timeline_id\"" + lineEnd);
dos.writeBytes(lineEnd);
// assign value
dos.writeBytes(timeline_id);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
//Send Image
Log.e("Sending", "Sending Image");
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"url\";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();
Log.e("ResponseCode", String.valueOf(serverResponseCode));
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(UploadProfilePicActivity.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(UploadProfilePicActivity.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(UploadProfilePicActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file failed", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
Simply use the below method to send multiple files with json request...
mImagePath is the arraylist of image paths
// Method for sending files using multiparting......
public static String sendJsonWithFile(Activity mActivity, ArrayList<String> mImagePaths, String jsonString, String URL)
{
Log.e("json", jsonString);
String res = "";
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
boundary = "--" + boundary;
httppost.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
StringBody stringBody = new StringBody(jsonString);
reqEntity.addPart("formstring", stringBody);
for (int i = 0; i < mImagePaths.size(); i++)
{
String imagePath = mImagePaths.get(i);
if (mImagePaths != null && mImagePaths.size() > 0)
{
byte[] filebytes = FileUtils.readFileToByteArray(new File(imagePath));
ByteArrayBody filebodyImage = new ByteArrayBody(filebytes, "image");
Log.e("file path=", filebodyImage.toString());
reqEntity.addPart("image", filebodyImage);
}
}
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null)
{
res = EntityUtils.toString(resEntity);
System.out.println(res);
}
if (resEntity != null)
{
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
catch (UnsupportedEncodingException e)
{
res = "UnsupportedEncodingException";
e.printStackTrace();
}
catch (ClientProtocolException e)
{
res = "ClientProtocolException";
e.printStackTrace();
}
catch (FileNotFoundException e)
{
res = "FileNotFoundException";
e.printStackTrace();
}
catch (IOException e)
{
res = "IOException";
e.printStackTrace();
}
catch (Exception e)
{
res = "Exception";
e.printStackTrace();
}
return res;
}
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();
I have made a form activity in android which contains some textfields and photo,I want to send this parameters to server
I am able to uplaod all other parameters successfully,But image is not uploading to server,Please help me save me..Thank you,My code is as below:
code
Bitmap bitmap;
onClick(){
editEnable();
System.out.println("::::::::::save clicked:::::::::");
header.edit.setVisibility(View.GONE);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
// new EditProfileAPI().execute();
new ImageUploadTask().execute();
// Profile Edit Call...!!!
break;
}
class ImageUploadTask extends AsyncTask<Void, Void, String> {
private StringBuilder s;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Loading");
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(Void... unsued) {
try {
String sResponse = "";
String url = Const.API_eDIT_PROFILE + "?";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("customer_id", new StringBody(Pref.getValue(HomeActivity.this, Const.PREF_CUSTOMER_ID, "")));
entity.addPart("first_name", new StringBody(et_firstname.getText().toString().trim()));
entity.addPart("last_name", new StringBody(et_lastname.getText().toString().trim()));
entity.addPart("customer_add", new StringBody(tv_adres.getText().toString().trim()));
entity.addPart("customer_phone", new StringBody(tv_phone.getText().toString().trim()));
entity.addPart("business_info", new StringBody(tv_busines.getText().toString().trim()));
entity.addPart("business_type", new StringBody(tv_busines_typ.getText().toString().trim()));
entity.addPart("bank_ac", new StringBody(tv_bank_acnt.getText().toString().trim()));
entity.addPart("dr_cr_card", new StringBody(tv_card.getText().toString().trim()));
entity.addPart("purpose_code", new StringBody(et_purpose_code.getText().toString().trim()));
entity.addPart("paypal_email", new StringBody(tv_paypal_email.getText().toString().trim()));
entity.addPart("password", new StringBody(et_fpassword.getText().toString().trim()));
entity.addPart("filename", new StringBody("test2.jpg"));
entity.addPart("files[]", new ByteArrayBody(data, "image/jpeg", "test2.jpg"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return s.toString();
} else {
return "{\"status\":\"false\",\"message\":\"Some error occurred\"}";
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("::::::::::::::::::::::::::::MY exception in edit::::::::::::::::" + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String sResponse) {
try {
pDialog.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(), sResponse + " Photo uploaded successfully", Toast.LENGTH_SHORT).show();
System.out.println("::::::::::::::::::::::::::::MY SUCCESS RESPONESE in edit::::::::::::::::" + sResponse);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Upload image or media file
public void doFileUpload(String videoPath) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = videoPath;
String str = "";
System.out.println("(Talk)videoPath" + existingFileName);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10 1024 1024;
try {
// ------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(
existingFileName));
// open a URL connection to the Servlet
URL url = new URL(url1);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ existingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}