我想将我的图像数据(文件)和字符串数据(用户名)从android上传到服务器上的mysql数据库
我的JSON代码:
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("file",ba1));
nameValuePairs.add(new BasicNameValuePair("username",nama));
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();
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());
}
}
和我的PHP代码:
<?php
include_once("koneksi.php");
$username = $_REQUEST['username'];
$file = $_REQUEST['file'];
$hasil = mysql_query("select (max(ID)+1)as newid from userownfile");
$row = mysql_fetch_row($hasil);
$base = $_REQUEST['file'];
$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");
if($username && $file){
$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);
?>
我在数据库上的表应该是这样的:
ID |用户名|文件
但是当我尝试上传时,图像和用户名没有插入我的数据库,我错过了什么?有谁可以帮我修复代码?
之前谢谢答案 0 :(得分:0)
使用类似Fiddler的东西来确保您发送到服务器的数据包是服务器所期望的数据包。
如果您想将文本格式化为JSON,我建议您使用内置类并执行以下操作:
JSONObject json = new JSONObject();
json.put("file", ba1);
json.put("username", nama);