i use java.net.URLConnection to send image and some parameters to server using POST method. My code below is works fine to send image to server, but i'm bit confused to attach some parameter and send to server in one time. I've followed here and here but i think its different method with my code.
Here is my snippet code bellow :
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.util.Log;
import android.widget.Toast;
import com.yai.app.support.DialogHandler;
public class ThreadImageUploader {
private int serverResponseCode = 0;
private ProgressDialog dialog;
private Activity activity;
public ThreadImageUploader(ProgressDialog mProgressDialog, Activity mActivity){
dialog = mProgressDialog;
activity = mActivity;
}
public int uploadFile(final String sourceFileUri, final String upLoadServerUri) {
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 : " + sourceFileUri);
activity.runOnUiThread(new Runnable() {
public void run() {
new DialogHandler().customDialog(activity, "ERROR", "Source File not exist : " + sourceFileUri);
}
});
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){
activity.runOnUiThread(new Runnable() {
public void run() {
String message = "File Upload Completed.";
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "MalformedURLException : : check script url.", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
}
}
How i can send image and some parameter to server in one time?
many thanks.
Finally, here its solution for my problem. The code snippet bellow can use to upload image and send text to server. Maybe this post can help others :)
Here is the code :
public int uploadFile(final String sourceFileUri, final String upLoadServerUri, final String renameFile) {
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 : " + sourceFileUri);
activity.runOnUiThread(new Runnable() {
public void run() {
new DialogHandler().customDialog(activity, "ERROR", "Source File not exist : " + sourceFileUri);
}
});
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", renameFile);
dos = new DataOutputStream(conn.getOutputStream());
// add parameters
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"type\""
+ lineEnd);
dos.writeBytes(lineEnd);
// assign value
dos.writeBytes("Your value");
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
// send image
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename='"
+ renameFile + "'" + 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){
activity.runOnUiThread(new Runnable() {
public void run() {
String message = "File Upload Completed.";
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "MalformedURLException : : check script url.", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
}
Related
I have a code.
Frontend:
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn;
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+uploadFilePath + "" + uploadFileName);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=" + fileName + " + lineEnd");
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necessary 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 "
+uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
Backend:
$file_path = "uploads/files/";
$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";
}
This code works, but:
I can't upload small files (10-1000 bytes), there is no errors in server response, but I don't see any small files
Big files changes, for example I send 3925 bytes size file to server, but server saves only 1002 bytes (end of the file). 26216 bytes -> 26173 etc.
Can you help me what a reason of such strange error, or maybe you have an idea how to fix it?
Thanks.
UPDATE:
Looks like I've solved the problem. There is a new code, works fine. Key solution - to use System.lineSeparator() instead String lineEnd = "\r\n";:
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn;
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
//String boundary = "*****file_Antares*****";
String boundary = "WebKitFormBoundary7$G67whGfe341h6#fr561";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 8*1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+uploadFilePath + "" + uploadFileName);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpsURLConnection) 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);
conn.connect(); //new!!!
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + System.lineSeparator());// add new System.lineSeparator())
dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=" + fileName + System.lineSeparator());
dos.writeBytes(System.lineSeparator());
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
while ((bytesRead = fileInputStream.read(buffer)) >= 0) {
dos.write(buffer, 0, bytesRead);
}
// send multipart form data necessary after file data...
dos.writeBytes(System.lineSeparator());
dos.writeBytes(twoHyphens + boundary + twoHyphens + System.lineSeparator());
//close the streams //
dos.close();
dos.flush();
fileInputStream.close();
// 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"
+uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
You call conn.getResponseCode(); too early.
Doing so ends the request, but your code to flush and close dos will be executed a lot later:
dos.flush(); // can be omitted as close is called directly afterwards
dos.close();
Move this code block before conn.getResponseCode();.
Additionally your while loop is defect because you always write buferSize instead of bytesRead bytes to dos. Also the whole calculations about buffer size is totally unnecessary. Just use a fixed size buffer instead, that will always work.
buffer = new byte[8192];
bytesRead = fileInputStream.read(buffer);
while (bytesRead >= 0) {
dos.write(buffer, 0, bytesRead);
bytesRead = fileInputStream.read(buffer);
}
Or shorter:
buffer = new byte[8192];
while ((bytesRead = fileInputStream.read(buffer)) >= 0) {
dos.write(buffer, 0, bytesRead);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.close();
Using this code I can upload files to the server. but I want to pass some other values to the php code to insert that value to database. but with the code I am using I couldn't make it
Here is the code i wrote for onClickListenter
public void onClick(View v) {
if(v== ivAttachment){
//on attachment icon click
showFileChooser();
}
if(v== bUpload){
final String arippe = "arippe";
//on upload button Click
if(selectedFilePath != null){
dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);
new Thread(new Runnable() {
#Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedFilePath, arippe);
}
}).start();
}else{
Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
}
}
}
Here is UploadFile function code
public int uploadFile(final String selectedFilePath, String arippe){
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedFilePath);
String[] parts = selectedFilePath.split("/");
final String fileName = parts[parts.length-1];
if (!selectedFile.isFile()){
dialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
}
});
return 0;
}else{
try{
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file",selectedFilePath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"arippe\""
+ lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(arippe);
dataOutputStream.writeBytes(lineEnd);
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ selectedFilePath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer,0,bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0){
//write the bytes read from inputstream
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
//response code of 200 indicates the server status OK
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
#Override
public void run() {
tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://coderefer.com/extras/uploads/"+ fileName);
}
});
}
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,"File Not Found",Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "URL error!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
return serverResponseCode;
}
}
and here is the php code
$file_path = "uploads/";
$a = "areef";
$b = $_POST['arippe'];
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
$c = $file_path;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
} else{
echo "fail";
}
$sql_query = "insert into users(name, user_name, user_pass) values('$a', '$b', '$c')";
mysqli_query($mysqli, $sql_query);
When I click upload button null value is posted to user_name
Well...you can use multipart request to upload data...
There are so many ways to upload data on server...
1- By using Volley networking library
https://developer.android.com/training/volley/index.html
2- by using retrofit library
http://square.github.io/retrofit/
Best way is to use Volley networking library..because Google Android recommended to use volley for any network operation.
Simple way is to use HttpUrlConnection class to upload data on server.
Im using the code below to upload an image to the server using java and PHP, i works fine, but i would like to resize the image before upload to the server, can some help me how to do that THANKS!!
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) {
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
}
}
And php code is
< ?php
$file_path = "uploads/";
$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 could always try : http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/
Very easy to use.
then you just do :
BufferedImage image = ImageIO.read(file);
image = Scalr.resize(image, 150);
in the .resize you pass in the imgFile and then the size you want. I put 150 here just as an example
Not sure what is going on here, not getting any red errors, but the post for the image never occurs, it is not touching my servers...
Here is the error in orange:
01-18 06:36:48.372: W/InputEventReceiver(7867): Attempted to finish an input event but the input event receiver has already been disposed.
01-18 06:36:48.372: W/InputEventReceiver(7867): Attempted to finish an input event but the input event receiver has already been disposed.
01-18 06:36:48.372: I/Choreographer(7867): Skipped 87 frames! The application may be doing too much work on its main thread.
01-18 06:36:48.372: W/ViewRootImpl(7867): Dropping event due to root view being removed: MotionEvent { action=ACTION_UP, id[0]=0, x[0]=287.0, y[0]=-358.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=5442878, downTime=5442722, deviceId=0, source=0x1002 }
01-18 06:37:31.392: I/uploadFile(7867): HTTP Response is : Internal Server Error: 500
01-18 06:37:31.522: E/Async Time(7867): Async entered POSTTTT
Here is the code:
private class ImageUploadTask extends AsyncTask<String, Void, String> {
private String webAddressToPost = "http://10.0.2.2:3000/wardrobe";
// File sourceFile = new File(imageview);
String fileName = "/sdcard/IMG_2016.JPG";
File sourceFile = new File(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;
// private ProgressDialog dialog
private ProgressDialog progressDialog = new ProgressDialog(
wardrobe.this);
#Override
protected void onPreExecute() {
Log.e("Async Time", "Async entered 1 PREEE");
progressDialog.setMessage("Uploading...");
progressDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
Log.e("Async Time", "Async entered DURINGG");
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(webAddressToPost);
// 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) {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ " F:/wamp/wamp/www/uploads";
imageTextSelect.setText(msg);
Toast.makeText(wardrobe.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.e("Async Time", "Async entered POSTTTT");
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "file uploaded",
Toast.LENGTH_LONG).show();
}
}
Your giving directly as sdcard String fileName = "/sdcard/IMG_2016.JPG"; may be that's the reason.
Try like below codes..
String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/IMG_2016.JPG";
I am making an app that will upload image which is taken from android phone. In my current code one of my if condition becomes true that return 0 and due to which my function stop working and it also does not upload image to server.
Here is my code
public class Camera extends Activity {
ImageView ivUserImage;
Button bUpload;
Intent i;
int CameraResult = 0;
Bitmap bmp;
int serverResponseCode = 0;
ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
openCamera();
}
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
//Log.e("Image: ", data.toString());
bmp = (Bitmap) extras.get("data");
ivUserImage.setImageBitmap(bmp);
bUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog = ProgressDialog.show(Camera.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//tv.setText("uploading started.....");
Toast.makeText(getBaseContext(), "File is uploading...", Toast.LENGTH_LONG).show();
}
});
int response= uploadFile(bmp.toString());
//Log.e("Response: ", response);
System.out.println("RES : " + response);
}
}).start();
}
});
}
}
public int uploadFile(String sourceFileUri) {
String upLoadServerUri = "http://www.example.info/androidfileupload/index.php";
String fileName = sourceFileUri;
//Toast.makeText(getApplicationContext(), sourceFileUri, Toast.LENGTH_LONG).show();
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()) {
Log.e("uploadFile", "Source File Does not exist");
return 0;
}
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
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);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
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() {
//tv.setText("File Upload Completed.");
Toast.makeText(Camera.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
Toast.makeText(Camera.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
Toast.makeText(Camera.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
}
In my uploadFile() method this condition becomes true if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
return 0;
}.
How can I solve this problem the upload image which is taken from camera?
Update
Here is my logcat
06-10 16:30:08.595: D/CLIPBOARD(27966): Hide Clipboard dialog at Starting input: finished by someone else... !
06-10 16:30:10.305: D/PhoneWindow(27966): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView#4053eca0 has no id.
06-10 16:30:10.980: D/CLIPBOARD(27966): Hide Clipboard dialog at Starting input: finished by someone else... !
06-10 16:30:11.015: W/IInputConnectionWrapper(27966): showStatusIcon on inactive InputConnection
06-10 16:32:18.005: D/PhoneWindow(27966): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView#4053eca0 has no id.
06-10 16:32:38.890: D/dalvikvm(27966): GC_EXTERNAL_ALLOC freed 101K, 46% free 3097K/5639K, external 879K/1025K, paused 37ms
06-10 16:37:19.145: D/PhoneWindow(27966): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView#4053eca0 has no id.
06-10 16:39:01.805: E/uploadFile(27966): Source File Does not exist
06-10 16:39:01.805: I/System.out(27966): RES : 0
06-10 16:39:09.185: D/PhoneWindow(27966): couldn't save which view has focus because the focused view com.android.internal.policy.impl.PhoneWindow$DecorView#4053eca0 has no id.
06-10 16:39:09.475: D/CLIPBOARD(27966): Hide Clipboard dialog at Starting input: finished by someone else... !
How can I solve this problem the upload image which is taken from
camera?
Following Snippet will help you.
public void UploadImage(Bitmap bm) throws Exception {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://www.example.info/androidfileupload/index.php");
ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded", bab);
reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
}
you send bitmap string via this line
int response= uploadFile(bmp.toString());
Here you send Bitmap String. Do not send path of the images. so this (!sourceFile.isFile()) line do not found any file path.
I think that make a problem.
you debug you code that help you to find problem.
Thanks