i want to upload a image from android to my sql database, and i have a code like this :
private void uploadFile() {
// TODO Auto-generated method stub
Bitmap bitmapOrg= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() +"/Chart1.png");
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList nameValuePairs = new
ArrayList();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://ipadress/base.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
but at the same time i want to upload my username too to my database(let's say i retreive the username using edittext), anyone know how to do that? what kind of code that i should add? thanks before
my table in database should be like this :
ID | Username | file |
and the JSON code which i can use to upload string data is like this :
private void uploadFile() {
// TODO Auto-generated method stub
String nama = getIntent().getStringExtra("user");
Bitmap bitmapOrg= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() +"/Chart1.png");
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
nameValuePairs.add(new BasicNameValuePair("username",nama));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://139.195.144.67/BloodGlucose/base2.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
开发者_运维知识库 is = entity.getContent();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpRespose = httpclient.execute(httppost);
HttpEntity httpEntity = httpRespose.getEntity();
InputStream in = httpEntity.getContent();
BufferedReader read = new BufferedReader(new InputStreamReader(in));
String isi= "";
String baris= "";
while((baris = read.readLine())!=null){
isi+= baris;
}
//Jika isi tidak sama dengan "null " maka akan tampil Toast "Register Success" sebaliknya akan tampil "Register Failure"
if(!isi.equals("null")){
Toast.makeText(this, "Register Success", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Register Failure", Toast.LENGTH_LONG).show();
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
can i combine these code? or is there another way to upload file and string at the same time from android? thanks before
my php code :
<?php
include_once("koneksi.php");
$username = $_REQUEST['username'];
$hasil = mysql_query("select (max(ID)+1)as newid from userownfile");
$row = mysql_fetch_row($hasil);
$base = $_REQUEST['image'];
$filename = $row[0] . ".jpg";
$buffer=base64_decode($base);
$path = "img/".$filename.".jpg";
$handle = fopen($path, 'wb');
$numbytes = fwrite($handle, $buffer);
fclose($handle);
$conn=mysql_connect("localhost","root","");
mysql_select_db("db_bloodglucose");
$sql = "insert into userownfile(username,file) values('$username','" . $path . "')";
mysql_query($sql);
$string= "select * from userownfile";
$my_string= mysql_query($string);
if($my_string){
while($object= mysql_fetch_assoc($my_string)){
$output[] = $object;
}
echo json_encode($output);
?>
In my approach I used org.apache.http.entity.mime.MultipartEntity and added passed the image file name as a FileBody
entity.addPart("image_" + photo_count, new FileBody(
new File(failed.getFilenames()[i])));
then pass the MultiPartEntity to the HttpPost. I haven't posted full code since its got loads of comments and code unrelated to your question. By passing the image as a FileBody it is possible to get the image using stand php file handling code (See Below).
if ((!empty($_FILES[$im])) && ($_FILES[$im]['error'] == 0)) {
$newname = dirname(__FILE__) . '/../photo/' . $campaign . '/' . $fn;
if (!file_exists($newname)) {
if (move_uploaded_file($_FILES[$im]['tmp_name'], $newname)) {
//$resp = "The file " . $fn . " has been uploaded";
//printf("%s", $resp);
} else {
$error = $error + 1;
}
}else{
//image file already exists
$error = $error + 1;
}
} else {
$error = $error +1;
}
For my purpose the code above was in a loop as I was dealin with multiple images
$im = 'image_' . $i;
refers to the name of the image in the entity.
Sorry for the short post i'm rushed for time.
Forgot to mention the reason why I didn't use the Base64 string approach is it limits the size of the image that you can send. The FileBody approach in the entity was the best approach I found.
You can pass strings using:
entity.addPart("address", new StringBody(failed[0].getAddress()));
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 20000); // Timeout
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("address", new StringBody("my address example"));
entity.addPart("image_0", new FileBody(new File("filename of image")));
HttpPost post = new HttpPost("server address");
post.setEntity(entity);
HttpResponse response = client.execute(post);
Yes you can, and you should, to minimise the number of calls you make to the server. Just add another parameter to your nameValuePairs
with the appropriate data.
nameValuePairs.add(new BasicNameValuePair("image", image));
nameValuePairs.add(new BasicNameValuePair("username", username));
This is quite straight forward. What you should be looking at really is the server-side code as this needs to be able to handle the different pieces of data.
精彩评论