[英]JSON and upload image to server
我想將圖像從android上傳到我的sql數據庫,並且我有這樣的代碼:
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());
}
}
但是同時我也想將我的用戶名也上傳到我的數據庫(假設我使用edittext檢索用戶名),有人知道該怎么做嗎? 我應該添加哪種代碼? 之前感謝
我的數據庫表應該是這樣的:
ID | 用戶名| 文件
我可以用來上傳字符串數據的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("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());
}
我可以合並這些代碼嗎? 還是有另一種方式同時從android上傳文件和字符串? 之前感謝
我的PHP代碼:
<?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);
?>
在我的方法中,我使用了org.apache.http.entity.mime.MultipartEntity並將圖像文件名作為FileBody添加
entity.addPart("image_" + photo_count, new FileBody(
new File(failed.getFilenames()[i])));
然后將MultiPartEntity傳遞給HttpPost。 我沒有發布完整的代碼,因為它包含與您的問題無關的注釋和代碼。 通過將圖像作為FileBody傳遞,可以使用標准php文件處理代碼來獲取圖像(請參見下文)。
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;
}
出於我的目的,上面的代碼處於循環中,因為我要處理多個圖像
$im = 'image_' . $i;
指實體中圖像的名稱。
對不起,我趕時間來了。
忘記提及我之所以不使用Base64字符串方法的原因是它限制了您可以發送的圖像大小。 我發現實體中的FileBody方法是最好的方法。
您可以使用以下方式傳遞字符串:
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);
是的,您可以並且應該最大程度地減少對服務器的呼叫次數。 只需將帶有適當數據的另一個參數添加到您的nameValuePairs
。
nameValuePairs.add(new BasicNameValuePair("image", image));
nameValuePairs.add(new BasicNameValuePair("username", username));
這很簡單。 您真正應該看的是服務器端代碼,因為這需要能夠處理不同的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.