I have searched many sites to know how to upload image to server.I have seen one sample example.But it is not reading imaging from internal memory of phone.
I have included MainActivity.java file.Any suggestions please..
MainActivity.java
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
imageview = (ImageView)findViewById(R.id.imageView_pic);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://192.168.0.15/UploadToServer.php";
}
#Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.v("Upload image", ""+data);
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(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 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 :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
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"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.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(MainActivity.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(MainActivity.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
}
}
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("key", new StringBody("file"));
File file = new File(selectedImagePath);
multipartEntity.addPart("file", new FileBody(file));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
and the response methode:
private class PhotoUploadResponseHandler implements ResponseHandler<Object> {
#Override
public Object handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
HttpEntity r_entity = response.getEntity();
// String responseString = EntityUtils.toString(r_entity);
return null;
}
}
Use multipart in android, download httpmime-4.2.5.jar and add you libs folder http://grepcode.com/snapshot/repo1.maven.org/maven2/org.apache.httpcomponents/httpmime/4.2.5
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
try this code..
String url = "";
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("file", new FileSystemResource(your filename path));
RestTemplate rest = RestUtil.getRestTemplate();
rest.postForObject(url, parts, returnclassname.class);
return null;
thank you..
The server side code remains the same for both browser based and mobile apps, to upload an file. File upload requires a multipart post request.
Uploading an image is same as uploading a file with a specified content type image/*. You can mimic the request using Apache's HttpClient. Also remember to perform the upload in the separate thread.
Here's an example.
Please check your android manifest file. Have u allowed all these in your manifest.?
Sorry I m missing some permissions please google them.
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Related
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'];
}
?>
I have this code that allows me to select a file and upload it to a server.
Whenever I test it, it always says "File do not exist", I test it with different file explorer, but it's always the same message.
This is UploadFilesToServer.java
package com.example.hp.test;
/**
* Created by Haroun SMIDA on 8/8/2015.
*/
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hp.test.app.AppConfig;
public class UploadFilesToServer extends Activity implements OnClickListener {
private TextView uploadStatus;
private Button btnUploadFile;
private Button btnSelectFIle;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private static final int FILE_SELECT_CODE = 0;
/**
* ******* File Path ************
*/
private String uploadFilePath = null;
private String uploadFileName = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadfile);
btnUploadFile = (Button) findViewById(R.id.btnUploadFile);
btnUploadFile.setOnClickListener(this);
btnSelectFIle = (Button) findViewById(R.id.btnSelectFile);
btnSelectFIle.setOnClickListener(this);
uploadStatus = (TextView) findViewById(R.id.uploadStatus);
/************* Php script path ****************/
upLoadServerUri = AppConfig.URL_UPLOAD;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSelectFile:
selectFile();
break;
case R.id.btnUploadFile:
dialog = ProgressDialog.show(UploadFilesToServer.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
uploadStatus.setText("uploading started.....");
}
});
Log.i("File Path ", uploadFilePath);
Log.i("File Name ", uploadFileName);
uploadFile(uploadFilePath);
}
}).start();
;
break;
default:
break;
}
}
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 = 1024 * 1024;
File sourceFile = new File(sourceFileUri);
Log.i("File Uri ", sourceFileUri);
Log.i("File ", sourceFile.toString());
if (!sourceFile.exists()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+ uploadFilePath);
runOnUiThread(new Runnable() {
public void run() {
uploadStatus.setText("Source File not exist :"
+ uploadFilePath);
}
});
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;
uploadStatus.setText(msg);
Toast.makeText(UploadFilesToServer.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() {
uploadStatus.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadFilesToServer.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() {
uploadStatus.setText("Got Exception : see logcat ");
Toast.makeText(UploadFilesToServer.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
}
private void selectFile() {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select File"), FILE_SELECT_CODE);
uploadStatus.setText("Uploading file path :- '" + uploadFilePath+ "'");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == FILE_SELECT_CODE) {
Uri selectedFileUri = data.getData();
String uriString = selectedFileUri.toString();
File fileToUpload = new File(uriString);
uploadFilePath = fileToUpload.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getContentResolver().query(selectedFileUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
uploadFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
uploadFileName = fileToUpload.getName();
}
}
}
}
}
What is the right method that allows me to get the right path for the selected file?
I want to store images in a server via POST, the images that are sent are sent from the local storage cell, this my code asynchronous class in Android :
class ImageUpload extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... var) {
System.out.println(incidentId);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String[] q = mCurrentPhotoPath.split("/");
int idx = q.length - 1;
try {
File file = new File(mCurrentPhotoPath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(url_add_attachment);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + "image" + 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);
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
outputStream.writeBytes(lineEnd);
try {
outputStream.writeBytes(twoHyphens + lineEnd);
//outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(lineEnd);
//}
outputStream.writeBytes(twoHyphens + twoHyphens + lineEnd);
} catch (Exception e) {
e.printStackTrace();
}
int status = connection.getResponseCode();
InputStream in;
if(status >= HttpStatus.SC_BAD_REQUEST)
in = connection.getErrorStream();
else
in = connection.getInputStream();
inputStream = connection.getInputStream();
result = convertStreamToString(in);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
}
The server throws 400 error response also send me the exception :
java.io.FileNotFoundException: http://10.0.2.2/app_dev.php/incidents/8/attachments
MainActivity.java
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button)findViewById(R.id.uploadButton);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
messageText = (TextView)findViewById(R.id.messageText);
imageview = (ImageView)findViewById(R.id.imageView_pic);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://10.0.2.2/uploads/UploadToServer.php";
ImageView img= new ImageView(this);
}
#Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(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 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 :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
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"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.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(MainActivity.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(MainActivity.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
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/imageView_pic"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:src="#drawable/ic_launcher" />
<Button
android:id="#+id/button_selectpic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Picture" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click To Upload File"
android:id="#+id/uploadButton"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/messageText"
android:textColor="#000000"
android:textStyle="bold"
/>
</LinearLayout>
Mainfest file::
<uses-permission android:name="android.permission.INTERNET"/>
UploadToServer.php
<?php
$file_path = "../image upload folder name here/";
$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";
}
?>
You can pass your server url in following method to upload any file.Change file parameter in given code with your actual file.
public static HttpResponse uploadFile(String url) throws ClientProtocolException, IOException {
try {
// the file to be posted
String textFile = Environment.getExternalStorageDirectory() + "/file.txt";
// /.v(TAG, "textFile: " + textFile);
// Log.v(TAG, "postURL: " + url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 10000;
// HttpConnectionParams.setConnectionTimeout(httpParameters,
// timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
// HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
// post header
HttpPost httpPost = new HttpPost(url);
File file = new File(textFile);
FileBody fileBody = new FileBody(file);
MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.addPart("fileUpload", fileBody);
httpPost.setEntity(mBuilder.build());
return httpClient.execute(httpPost);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I have EditProfilAcitivity if i click imageview will select from gallery and no have problem. I have problem id i click button upload.
package net.drieanto.lagidimana;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.drieanto.lagidimana.library.AlertDialogManager;
import net.drieanto.lagidimana.library.ConnectionDetector;
import net.drieanto.lagidimana.library.UserFunctions;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class EditProfileActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout, buttonsearch;
EditText editSearch;
private ListView list;
private ArrayAdapter<String> adapter;
private RibbonMenuView rbmView;
private Button test;
private ListView rbmListView;
private ListView rbmListView2;
private ArrayAdapter<String> adapt;
private ArrayAdapter<String> adapter2;
ListView list1;
LazyAdapter adapter1;
private static int RESULT_LOAD_IMAGE = 1;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Connection detector
ConnectionDetector cd;
String selectedPath = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status in database
userFunctions = new UserFunctions();
if (userFunctions.isUserLoggedIn(getApplicationContext())) {
setContentView(R.layout.editprofile);
if (android.os.Build.VERSION.SDK_INT >= 11){
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.rgb(254,194,12)));
int actionBarTitleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
TextView actionBarTextView = (TextView)findViewById(actionBarTitleId);
actionBarTextView.setTypeface(null, Typeface.BOLD);
}
// Check if Internet present
cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(EditProfileActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
/** Menu **/
rbmView = (RibbonMenuView) findViewById(R.id.ribbonMenuView1);
list = (ListView) findViewById(R.id.listView1);
ProgressDialog progressDialog = new ProgressDialog(
EditProfileActivity.this);
progressDialog.setMessage("Loading...");
EditProfileTask EditProfileTask = new EditProfileTask(
EditProfileActivity.this, progressDialog);
EditProfileTask.execute();
ImageView image = (ImageView) findViewById(R.id.gambarAvatar);
image.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
editSearch = (EditText) findViewById(R.id.search);
buttonsearch = (Button) findViewById(R.id.buttonsearch);
buttonsearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent search = new Intent(getApplicationContext(),
SearchActivity.class);
search.putExtra("data", editSearch.getText().toString());
search.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(search);
finish();
}
});
/**
* This is an exmaple button it calls "hideMenu()" after each click
* similiar to the Facebook or Google+ apps
* **/
btnLogout = (Button) findViewById(R.id.buttonLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(),
LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
/**
* This is the most important ListView, updating the main list in
* the Activity
**/
final String[] items_list = { "Home", "Follower", "Request", "View Profile" };
adapt = new ArrayAdapter<String>(EditProfileActivity.this,
android.R.layout.simple_list_item_1, items_list);
rbmListView = (ListView) findViewById(R.id.rbm_listview);
rbmListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
Intent dashboard = new Intent(getApplicationContext(),
DashboardActivity.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();
break;
case 1:
Intent follower = new Intent(getApplicationContext(),
FollowerActivity.class);
follower.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(follower);
finish();
break;
case 2:
Intent request = new Intent(getApplicationContext(),
RequestActivity.class);
request.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(request);
finish();
break;
case 3:
Intent profil = new Intent(getApplicationContext(),
ProfilActivity.class);
profil.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(profil);
// Closing dashboard screen
finish();
break;
default:
break;
}
rbmView.hideMenu();
}
});
rbmListView.setAdapter(adapt);
} else {
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(),
LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
Button upload = (Button)findViewById(R.id.imguploadbtn);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
new ImageUpload().execute();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaColumns.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
selectedPath = getPath(selectedImage);
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
final String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.gambarAvatar);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/*private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://git.drieanto.net/upload/upload.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + selectedPath + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}*/
/**
* Allows users, even API < 5, to use the back button
*
* public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode)
* { case KeyEvent.KEYCODE_BACK: rbmView.hideMenu(); break; default: return
* super.onKeyDown(keyCode, event); } return true; }
*/
/**
* Options Menu<br>
* example toggle
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.test:
rbmView.toggleMenu();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
public void showEditError(int responseCode) {
int duration = Toast.LENGTH_LONG;
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Terjadi Error", duration);
toast.show();
}
public void showEditSuccess(int responseCode) {
int duration = Toast.LENGTH_LONG;
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Terjadi Error", duration);
toast.show();
}
class ImageUpload extends AsyncTask<Void, Void, String>{
#Override
protected void onProgressUpdate(Void... unsued) {
}
#Override
protected String doInBackground(Void... params) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://lagidimana.net/upload/upload.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + selectedPath + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return null;
}
}
}
upload.php file
<?php
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>
i have chmod 777 folder uploads/
Error Message in logcat in bottom, but i don't understand with this error. Maybe you have same problem.
06-14 21:46:35.339: E/Debug(13682): File is written
06-14 21:46:53.339: E/Debug(13682): Server Response There was an error uploading the file, please try again!filename: target_path: uploads/
please help thank's
You are calling the function doFileUpload from the Main UI thread. Android does not allow you to make Network calls on the main thread.
Build an Asynctask and do the upload process of connecting to the network from another thread (in the doInBackground function).
I tried uploading an audio file from android client to server but I'm getting following error on server console:
java.io.FileNotFoundException:D:\temp\sdcard\recording20605.3gpp (The system cannot find the path specified)
("D:\temp" is where I'm trying to store file from client on my server i.e in temp folder in D drive of my pc).
Plz help
Here is the code for Client and server
SERVER CODE
// Import required java libraries
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 9000 * 1024;
private int maxMemSize = 6 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new
DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("D:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}
------------------
CLIENT CODE
-----------------
package com.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
public class SampleclientActivity extends Activity {
private static final int SELECT_AUDIO = 2;
String selectedPath = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
openGalleryAudio();
}
public void openGalleryAudio(){
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Audio "), SELECT_AUDIO);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_AUDIO)
{
System.out.println("SELECT_AUDIO");
Uri selectedImageUri = data.getData();
selectedPath = getPath(selectedImageUri);
System.out.println("SELECT_AUDIO Path : " + selectedPath);
doFileUpload();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 4*1024*1024;
String responseFromServer = "";
String urlString = "http://123.236.177.244:8085/myproject1/UploadServlet";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + selectedPath + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
}
----------------------
AndroidManifest.xml
---------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.client"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.READ_OWNER_DATA"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SampleclientActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
Your filename contains an extra "\sdcard" which is trying to save the file in "sdcard" directory inside the "temp" directory. Ofcourse SDCARD is the directory not found on server so it is throwing exception. Either change the file name on runtime and remove "sdcard" from it or create the directory named "sdcard" inside "temp".
solution is:
private String filePath = "---your directory---"
private String filePath = "D:\temp\sdcard\"