I am trying to send values to PHP server but always,i get HTTP REsponse 200 and in my server i am not getting the value i sent,dont know what is the issue following is my snippet code for android and PHP,can any one help me with this?..sorry for to much code......i also followed this Android file upload - $_FILES returns empty
PHP side i used smarty framework
$print = false;
$header = true;
if(isset($_REQUEST['action']) && $_REQUEST['action'] =='imagetest')
{
$error = '0';
$val = basename($_FILES['image']['name']);
if($val != '')
{
$error = '1';
$msg = 'Image Not Upload Please Try Agin';
$param = array("status"=>"error","msg"=>$val);
$val = json_encode($param);
echo $val;
exit;
}
/*if($_FILES['image'] == '')
{
$error = '1';
$msg = 'Image Not Upload Please Try Agin';
$param = array("status"=>"error","msg"=>$msg);
$val = json_encode($param);
echo $val;
exit;
}*/
if($error == '0')
{
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
$msg = 'Image inserted successfully';
$param = array("status"=>"success","msg"=>$msg);
$val = json_encode($param);
echo $val;
exit;
} else{
$msg = 'Image not inserted successfully';
$param = array("status"=>"success","msg"=>$msg);
$val = json_encode($param);
echo $val;
exit;
}
}
}
else
{
$msg = 'something went wrong';
$param = array("status"=>"success","msg"=>$msg);
$val = json_encode($param);
echo $val;
exit;
}
MyjavaFile
uploadButton = (ImageView)findViewById(R.id.uploadButton);
uploadButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
dialog = ProgressDialog.show(PhotoUpload.this, "", "Uploading file...", true);
new Thread(new Runnable()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
messageText.setText("uploading started.....");
}
});
uploadFile(selectedImagePath);
}
}).start();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1111) {
if (data!=null ) {
openGalleryImage(data);
//saveImage(uri_outputFileUri.getPath());
Uri selectedImageUri = data.getData();
Bitmap bitmap;
try {
bitmap = scaleImage(PhotoUpload.this,selectedImageUri);
img.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static Bitmap scaleImage(Context context, Uri photoUri) throws IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = getOrientation(context, photoUri);
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
if (rotatedWidth > 100 || rotatedHeight > 100) {
float widthRatio = ((float) rotatedWidth) / ((float) 100);
float heightRatio = ((float) rotatedHeight) / ((float) 100);
float maxRatio = Math.max(widthRatio, heightRatio);
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
srcBitmap = BitmapFactory.decodeStream(is, null, options);
} else {
srcBitmap = BitmapFactory.decodeStream(is);
}
is.close();
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
srcBitmap.getHeight(), matrix, true);
}
String type = context.getContentResolver().getType(photoUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (type.equals("image/png")) {
srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
} else if (type.equals("image/jpg") || type.equals("image/jpeg")) {
srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
}
byte[] bMapArray = baos.toByteArray();
baos.close();
return BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
}
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
private void openGalleryImage(Intent data)
{
Uri selectedimg = data.getData();
Uri uriselectedimage=data.getData();
mString=uriselectedimage.getPath();
try
{
mInputStream= getContentResolver().openInputStream(selectedimg);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
String[] path = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedimg, path, null, null,null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(path[0]);
selectedImagePath=c.getString(columnIndex);
uri_outputFileUri= Uri.parse(selectedImagePath);
c.close();
}
private void saveImage(String mPath)
{
System.out.println("Paths "+mPath);
mediaDir= new File(Environment.getExternalStorageDirectory() +"/MyFolder");
mediaDir.mkdir();
File myImage = new File(mediaDir, Long.toString(System.currentTimeMillis()) + ".png");
try
{
FileOutputStream out = new FileOutputStream(myImage);
mbitmap_outputImage=BitmapFactory.decodeFile(mPath);
mbitmap_outputImage=Bitmap.createScaledBitmap(mbitmap_outputImage, 390, 310, true);
mbitmap_outputImage.compress(Bitmap.CompressFormat.PNG, 100, out);
img.setImageBitmap(mbitmap_outputImage);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@SuppressWarnings("deprecation")
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) {
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 :"
+ selectedImagePath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+ selectedImagePath);
}
});
return 0;
}
else
{
try {
/* btns=uploadButton.getTag().toString();
System.out.println(btns);*/
String fileName = sourceFileUri;
File f = new File(selectedImagePath);
imgs= f.getName();
System.out.println(imgs);
upLoadServerUri = "http://www.asdf.com/web-service/imagetest.php?action=imagetest&image="+imgs;
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
System.out.println(url);
// 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("image", imgs);
// conn.setRequestProperty("user_login_id", User_ID);
// conn.setRequestProperty("action", "addproduct");
// conn.setRequestProperty("version", "apps");
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
// send image
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name='image';filename='"
+ imgs + "'" + 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() {
@SuppressWarnings("deprecation")
public void run() {
try
{
DataInputStream dataIn = new DataInputStream(conn.getInputStream());
String inputLine;
while ((inputLine = dataIn.readLine()) != null)
{
result += inputLine;
System.out.println("Result : " + result);
}
//result=getJSONUrl(url); //<< get json string from server
//JSONObject jsonObject = new JSONObject(result);
JSONObject jobj = new JSONObject(result);
sta = jobj.getString("status");
msg = jobj.getString("msg");
System.out.println(sta + " >>>>>>> " + msg);
// new LoadImages().execute();
/* Intent intent=new Intent(PhotoUpload.this,PhotoView.class);
startActivity(intent);*/
}
catch (Exception e)
{
e.printStackTrace();
}
you can refer this nice tutorial "Android Uploading Camera Image, Video to Server with Progress Bar"
Try specifying the length of the file in the header. It seems some servers may reject the file if there is no Content-Length header. E.g.:
conn.setRequestProperty("Content-Length", Integer.toString(fileInputStream.available()));
来源:https://stackoverflow.com/questions/29299839/using-files-not-able-to-send-file-to-php-server