|
|
|
Andorid - ไม่สามารถอัพโหลด Upload รูปภาพขึ้น Server บน PHP ได้ รบกวนพี่แอดมินดูให้ทีนะครับ |
|
|
|
|
|
|
|
Code (Android-Java)
package com.softeng.myproject;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.MenuInflater;
import android.view.View;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class AddTemple extends Activity {
private static final int PICK_IMAGE = 1;
private ImageView imgView;
private Button upload;
private EditText caption;
private Bitmap bitmap;
private ProgressDialog dialog;
private TextView tv_file;
final String url = "http://appsofteng.com/student7/Project/addtemple.php";
String file_name;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_temple);
tv_file = (TextView)findViewById(R.id.tv_file);
tv_file.setText("");
imgView = (ImageView) findViewById(R.id.ImageView);
upload = (Button) findViewById(R.id.Upload);
caption = (EditText) findViewById(R.id.Caption);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//btnBack
final Button btnBack = (Button) findViewById(R.id.btnBack);
btnBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent ittemple = new Intent (getApplicationContext(),ManagerTemple.class);
startActivity(ittemple);
}
});
// btnSave
final Button btnSave = (Button) findViewById(R.id.btnSave);
// Perform action on click
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(SaveData())
{
// When Save Complete
}
}
});
}
public boolean SaveData()
{
final EditText txtName = (EditText) findViewById(R.id.txtName);
final EditText txtAddress = (EditText) findViewById(R.id.txtAddress);
final EditText txtLat = (EditText) findViewById(R.id.txtLat);
final EditText txtLong = (EditText) findViewById(R.id.txtLong);
upload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE);
}
});
// Dialog
final AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setTitle("Error! ");
ad.setIcon(android.R.drawable.btn_star_big_on);
ad.setPositiveButton("Close", null);
// Check Name
if(txtName.getText().length() == 0)
{
ad.setMessage("Please input [Name] ");
ad.show();
txtName.requestFocus();
return false;
}
// Check Lat
if(txtLat.getText().length() == 0)
{
ad.setMessage("Please input [Lattitude] ");
ad.show();
txtLat.requestFocus();
return false;
}
// Check Long
if(txtLong.getText().length() == 0)
{
ad.setMessage("Please input [Longtitude] ");
ad.show();
txtLong.requestFocus();
return false;
}
Log.d("OK","URL SUCCESS");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sName", txtName.getText().toString()));
params.add(new BasicNameValuePair("sAddress", txtAddress.getText().toString()));
params.add(new BasicNameValuePair("sLattitude", txtLat.getText().toString()));
params.add(new BasicNameValuePair("sLongtitude", txtLong.getText().toString()));
String resultServer = getHttpPost(url,params);
/*** Default Value ***/
String strStatusID = "1";
String strError = "Unknow Status!";
JSONObject c;
try {
c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Save Data
if(strStatusID.equals("0"))
{
ad.setMessage(strError);
ad.show();
}
else
{
Toast.makeText(AddTemple.this, "Save Data Successfully", Toast.LENGTH_LONG).show();
Intent it1 = new Intent (AddTemple.this,ManagerTemple.class);
startActivity(it1);
txtName.setText("");
txtAddress.setText("");
txtLat.setText("");
txtLong.setText("");
}
return true;
}
public String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = null;
try {
String filemanagerstring = selectedImageUri.getPath();
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
tv_file.setText(filePath);
File file = new File(filePath);
file_name=file.getName();
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
default:
}
}
class ImageUploadTask extends AsyncTask <Void, Void, String>{
String err=null;
@Override
protected String doInBackground(Void... unsued) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
ByteArrayBody bab = new ByteArrayBody(data,file_name);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("sImage", bab);
reqEntity.addPart("Image", new StringBody(caption.getText().toString().trim()));
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);
}
return s.toString().trim();
} catch (Exception e) {
err="error"+e.getMessage();
Log.e(e.getClass().getName(), e.getMessage());
return e.getMessage();
}
}
protected void onPostExecute(String res) {
if (dialog.isShowing())dialog.dismiss();
AlertDialog.Builder alertbox = new AlertDialog.Builder(AddTemple.this);
alertbox.setTitle("Information");
alertbox.setNeutralButton("Ok",null);
if(err!=null){
alertbox.setMessage("เกิดข้อผิดพลาด!!!\n"+res);
}else{
alertbox.setMessage(res);
}
alertbox.show();
}
}
public String getPath(Uri url) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(url, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else{
return null;
}
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
imgView.setImageBitmap(bitmap);
}
}
พี่แอดมินช่วยดูโค๊ดให้หน่อยทำไม ผมถึงอัพโหลดรูปภาพขึ้น server ไม่ได้ครับ
แต่เพิ่มข้อมูลได้อะครับ ชื่อ ที่อยู่ ละติจูด ลองติจูด
Tag : Mobile, MySQL, Android
|
|
|
|
|
|
Date :
2014-01-22 11:44:10 |
By :
phuwadonlove |
View :
1696 |
Reply :
10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
โค๊ดยาวเบื้ยยยยยย เยยยย
มันติดตรงสิทธิหรือเปล่าครับ
|
|
|
|
|
Date :
2014-01-22 13:27:13 |
By :
Dragons_first |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ยังไงหรือครับ ติดตรงสิทธิ รบกวนอธิบายหน่อยได้ไหมครับ
|
|
|
|
|
Date :
2014-01-22 13:45:02 |
By :
phuwadonlove |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
มีใครพอสามารถช่วยผมไหมคร้าบ T^T
|
|
|
|
|
Date :
2014-01-23 21:46:24 |
By :
phuwadonlove |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ผมลองสร้างแล้วครับมันสามารถอัพได้คับ แต่ใน Android ไม่สามารถอัพได้อะครับ
|
|
|
|
|
Date :
2014-02-10 13:38:32 |
By :
phuwadonlove |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
แล้วเรื่องการกำหนดขนาดของรูปมีส่วนเกี่ยวข้องกันไหมลองคิดดูน่ะครับ..บางครั้งขนาดส่งจากมือถือไฟล์ใหญ่เกินไปหรือเปล่า
|
|
|
|
|
Date :
2014-02-26 07:52:43 |
By :
manasak19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
จาก Error เหมือนว่า JSON มันแปลงค่าผิด อาจจะเกิดจากส่งค่ากลับมาผิดพลาดครับ
|
|
|
|
|
Date :
2014-02-26 08:34:39 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
น่าจะเออเร่อที่ มันไม่สามารถ convert string เป็น json object ป่าวคับลองเอา เออเร่อไปเสิทใน google ดูคับ
|
|
|
|
|
Date :
2014-02-26 22:05:37 |
By :
kaisiamza |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
มีวิธีแก้ไขอย่างไรบ้างครับ รบกวนด้วยนะครับ
ทักเฟสผมก็ได้ [email protected]
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);
ผมสงสัยว่ามันไม่มีคำสั่งนี้หรือเปล่า เหมือน PHP อะครับ
ไม่มี mutipart/form-data มันก็ไม่สามารถอัพรูปได้
|
|
|
|
|
Date :
2014-02-28 14:43:26 |
By :
phuwadonlove |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Date :
2014-02-28 17:41:52 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 03
|