Android:无法使用 php 脚本将图像上传到远程 MySql DB
Posted
技术标签:
【中文标题】Android:无法使用 php 脚本将图像上传到远程 MySql DB【英文标题】:Android: Impossible upload image to remote MySql DB with php script 【发布时间】:2013-01-28 21:07:57 【问题描述】:我在这个问题上花了 2 周时间。我写了下面的代码(android和php)。看起来还可以,但不能正常工作或不能正常工作。客户端Android似乎发送了一些东西服务器端收到了一些东西,但我不知道它是什么。
在客户端 Android 和服务器上的代码下方。
谢谢。
…
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
uri_Target=uriTarget.toString();
OutputStream imageFileOS;
try
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(ActSismicoCamera_New.this, "Image saved: " + uriTarget.toString(),Toast.LENGTH_LONG).show();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("percorso",uri_Target);
editor.commit();
inviaPosizione(uri_Target);
catch (FileNotFoundException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
camera.startPreview();
…
--------------------------------------------------------------------------------------
private void inviaPosizione(String percorso)
InputStream is=null;
try
String uri_Target;
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
uri_Target = preferences.getString("percorso", null);
Uri imageUri = Uri.parse(uri_Target);
String filenamelastPhoto;
filenamelastPhoto = getLastImage(imageUri);
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath()+ "/DCIM/Camera/");
File immagine = new File(directory, filenamelastPhoto); //or any other format supported
if(immagine.exists())
Toast.makeText(ActSismicoCamera_New.this, "ESISTE = "+immagine, Toast.LENGTH_LONG).show();
Bitmap bitmapOrg = BitmapFactory.decodeFile(immagine.toString());
ByteArrayOutputStream bao = new ByteArrayOutputStream();
try
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 60, bao);
byte [] ba = bao.toByteArray();
Toast.makeText(ActSismicoCamera_New.this, "inviaPosizione Valore ba= " + ba, Toast.LENGTH_LONG).show();
int flag = 1;
String ba1 = Base64.encodeBytes(ba,flag);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("tag","registra"));
nameValuePairs.add(new BasicNameValuePair("media",ba1));
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Custom user agent");
HttpPost httppost = new
HttpPost("http://xxxxx.org/AndActSismicoUploadFile.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
catch(Exception e)
Toast.makeText(ActSismicoCamera_New.this, "inviaPosizione Exception su HttpClient: " + e.toString(), Toast.LENGTH_LONG).show();
try
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
is.close();
json = sb.toString();
catch (Exception e)
Log.e("Buffer Error", "Error converting result " + e.toString());
catch (Exception e)
e.printStackTrace();
PHP 脚本
<?php
require_once 'DB_Funzioni.php';
if (isset($_POST['tag']) && $_POST['tag'] != '')
$tag = $_POST['tag'];
$oggetto = $_POST['media'];
if (isset($_POST['media']))
header('Content-Type: bitmap;charset-utf-8');
if(move_uploaded_file($_FILES["media"]["tmp_name"],"immagini/" . $_FILES["media"]["name"]))
echo "The file ". $_FILES['media']['name']." has been uploaded";
$info="The file ". basename( $_FILES['media']['name'])." has been uploaded";
mail ($destinatario, $ogg, $info);
else
$info="Problema!";
mail ($destinatario, $ogg, $info);
switch ($_FILES['media']['error'])
case 1:
echo "The uploaded file exceeds the upload_max_filesize directive in php.ini";
$info="The uploaded file exceeds the upload_max_filesize directive in php.ini!";
mail ($destinatario, $ogg, $info);
break;
case 2:
echo "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form";
$info="The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form!";
mail ($destinatario, $ogg, $info);
break;
case 3:
echo "Only part of the file was uploaded";
$info="Only part of the file was uploaded!";
mail ($destinatario, $ogg, $info);
break;
case 4:
echo "No file was uploaded";
$info="No file was uploaded!";
mail ($destinatario, $ogg, $info);
break;
case 6:
echo "Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3";
$info="Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3!";
mail ($destinatario, $ogg, $info);
break;
case 7:
echo "Failed to write file to disk. Introduced in PHP 5.1.0";
$info="Failed to write file to disk. Introduced in PHP 5.1.0!";
mail ($destinatario, $ogg, $info);
break;
case 8:
echo "A PHP extension stopped the file upload";
$info="A PHP extension stopped the file upload!";
mail ($destinatario, $ogg, $info);
break;
$response = array("tag" => $tag, "success" => 0, "error" => 0);
$db = new DB_Functions();
$fileName = $_FILES['media']['name'];
$tmpName = $_FILES['media']['tmp_name'];
$fileSize = $_FILES['media']['size'];
$fileType = $_FILES['media']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
move_uploaded_file($_FILES["media"]["tmp_name"],"immagini/" . $_FILES["media"]["name"]);
fclose($fp);
if(!get_magic_quotes_gpc())
$fileName = addslashes($fileName);
$file = $db->storeFile($fileName);
if ($file)
$response["success"] = 1;
//$response["filename"]["id"] = $file["filename"];
$response["filename"]= $tmpName ;
echo json_encode($response);
Else
// user failed to store
$response["error"] = 1;
//$response["error_msg"] = "Error occured in Insert";
$response["error_msg"] = mysql_error();
echo json_encode($response);
Else
$response = array("tag" => $tag, "success" => 0, "error" => 0);
$response["error"] = 1;
$response["error_msg"] = "Media vuoto";
echo json_encode($response);
//mysql_close();
?>
【问题讨论】:
总是很高兴看到非英文的变量名...这使得阅读代码变得如此简单易懂... 为什么不让它转储它得到的任何东西,也许还有 SERVER 变量到一个文件中进行调试? 我使用外部服务提供商。我该怎么做? 它无法工作,因为对于图片,您需要内容类型 multipart ... 在 android 中可能是“MultiPartEntity”?见:useandgain.blogspot.de/2012/06/… 【参考方案1】:这不是一个完整的答案......我会在我们进行的过程中完成这个答案......
首先,我建议您检查您是否获得了您应该获得的帖子数据。请将其插入到顶部之后:
if (isset($_POST['tag']) && $_POST['tag'] != '')
...
file_put_contents ("mydebugdata.txt",json_encode($_POST));
这应该将脚本接收的数据转储到文件“mydebugdata.txt”... json_encode() 给 $_POST 一些结构......所以你可以读取数据......
然后尝试保存图片并在此处发布 mydebugdata.txt 的内容...
【讨论】:
以上是关于Android:无法使用 php 脚本将图像上传到远程 MySql DB的主要内容,如果未能解决你的问题,请参考以下文章