Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从android将图像上载到php web服务器不工作_Java_Php_Android_Java Io - Fatal编程技术网

Java 从android将图像上载到php web服务器不工作

Java 从android将图像上载到php web服务器不工作,java,php,android,java-io,Java,Php,Android,Java Io,我正在使用相机拍摄一幅图像,然后将图像上传到php web服务器。没有生成错误,但当我查看图像的目标文件夹时,没有任何错误。 代码如下: //for camera intent addphoto.setOnClickListener(new OnClickListener() { //LAUNCH CAMERA @Override public void onClick(View v) { // TODO Auto-generated method

我正在使用相机拍摄一幅图像,然后将图像上传到php web服务器。没有生成错误,但当我查看图像的目标文件夹时,没有任何错误。 代码如下:

//for camera intent

  addphoto.setOnClickListener(new OnClickListener() {
    //LAUNCH CAMERA
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent cameraintnent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
         startActivityForResult(cameraintnent, 1);



    }
});
这是onActivityResult()方法代码

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1) {
    //for camera        

     bitmapOrg= (Bitmap) data.getExtras().get("data");              
     String outPut = null;

     ByteArrayOutputStream bao = new ByteArrayOutputStream();

     //Resize the image
     double width = bitmapOrg.getWidth();
     double height = bitmapOrg.getHeight();
     double ratio = 400/width;
     int newheight = (int)(ratio*height);          
     bitmapOrg = Bitmap.createScaledBitmap(bitmapOrg, 400, newheight, true);

     bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 95, bao);
     byte[] ba = bao.toByteArray();
     String ba1 = Base64.encodeBytes(ba);

     ArrayList<NameValuePair> nameValuePairs = new

             ArrayList<NameValuePair>();

             nameValuePairs.add(new BasicNameValuePair("image",ba1)); 
     try {
         HttpClient httpclient = new DefaultHttpClient();
         HttpPost httppost = new HttpPost("http://localhost/m/upload.php");
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          Log.d("image uploading","The image is  uploading");
         HttpResponse response = httpclient.execute(httppost);
         HttpEntity entity = response.getEntity();               

         // print response
         outPut = EntityUtils.toString(entity);
         Log.i("GET RESPONSE—-", outPut);

         //is is the InputStream declared globally within the class
         is = entity.getContent();
         Log.e("log_tag ******", "good connection");

         bitmapOrg.recycle();

     } catch (Exception e) {
         Log.e("log_tag ******", "Error in http connection " + e.toString());
     }


    image.setImageBitmap(bitmapOrg); 
    setContentView(parentContainer);

}
@覆盖
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
if(requestCode==1){
//照相机
bitmapOrg=(位图)data.getExtras().get(“数据”);
字符串输出=null;
ByteArrayOutputStream bao=新建ByteArrayOutputStream();
//调整图像大小
double-width=bitmapOrg.getWidth();
double height=bitmapOrg.getHeight();
双倍比=400/宽;
int newheight=(int)(比率*高度);
bitmapOrg=Bitmap.createScaledBitmap(bitmapOrg,400,newheight,true);
compress(Bitmap.CompressFormat.JPEG,95,bao);
字节[]ba=bao.toByteArray();
字符串ba1=Base64.encodeBytes(ba);
ArrayList nameValuePairs=新建
ArrayList();
添加(新的BasicNameValuePair(“图像”,ba1));
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://localhost/m/upload.php");
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
Log.d(“图像上传”,“图像正在上传”);
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
//打印响应
输出=EntityUtils.toString(实体);
i(“获取响应--”,输出);
//是在类中全局声明的InputStream
is=entity.getContent();
Log.e(“Log_tag*******”,“良好连接”);
bitmapporg.recycle();
}捕获(例外e){
Log.e(“Log_标记*******,“http连接错误”+e.toString());
}
image.setImageBitmap(bitmapOrg);
setContentView(父容器);
}
这是php代码:

<?php

$base = $_REQUEST["image"];

if (isset($base)) {

$suffix = createRandomID();
$image_name = "img_".$suffix."_".date("Y-m-d-H-m-s").".jpg";

// base64 encoded utf-8 string
$binary = base64_decode($base);

// binary, utf-8 bytes

header("Content-Type: bitmap; charset=utf-8");

$file = fopen("../images/post_images/" . $image_name, "wb");

fwrite($file, $binary);

fclose($file);

die($image_name);

} else {

die("No POST");
}

function createRandomID() {

$chars = "abcdefghijkmnopqrstuvwxyz0123456789?";
//srand((double) microtime() * 1000000);

$i = 0;

$pass = "";

while ($i <= 5) {

$num = rand() % 33;

$tmp = substr($chars, $num, 1);

$pass = $pass . $tmp;

$i++;
 }
return $pass;
}
?>

问题在哪里?如何解决?

我已经为文件上传创建了doFileUpload()。首先上传简单文件,然后使用startActivityForResult

  private void doFileUpload(){
      HttpURLConnection conn = null;
      DataOutputStream dos = null;
      DataInputStream inStream = null; 


      String exsistingFileName = "/sdcard/six.3gp";
      // Is this the place are you doing something wrong.

      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary =  "*****";


      int bytesRead, bytesAvailable, bufferSize;

      byte[] buffer;

      int maxBufferSize = 1*1024*1024;

      String urlString = "http://192.168.1.5/upload.php";



      try
      {


      Log.e("MediaPlayer","Inside second Method");

      FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );



       URL url = new URL(urlString);

       conn = (HttpURLConnection) url.openConnection();

       conn.setDoInput(true);

       // Allow Outputs
       conn.setDoOutput(true);

       // Don't use a cached copy.
       conn.setUseCaches(false);

       // Use a post method.
       conn.setRequestMethod("POST");

       conn.setRequestProperty("Connection", "Keep-Alive");

       conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);


       dos = new DataOutputStream( conn.getOutputStream() );

       dos.writeBytes(twoHyphens + boundary + lineEnd);
       dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
       dos.writeBytes(lineEnd);

       Log.e("MediaPlayer","Headers are written");



       bytesAvailable = fileInputStream.available();
       bufferSize = Math.min(bytesAvailable, maxBufferSize);
       buffer = new byte[bufferSize];



       bytesRead = fileInputStream.read(buffer, 0, bufferSize);

       while (bytesRead > 0)
       {
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
       }



       dos.writeBytes(lineEnd);

       dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

       BufferedReader in = new BufferedReader(
                       new InputStreamReader(
                       conn.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) 
                tv.append(inputLine);




       // close streams
       Log.e("MediaPlayer","File is written");
       fileInputStream.close();
       dos.flush();
       dos.close();


      }
      catch (MalformedURLException ex)
      {
           Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
      }

      catch (IOException ioe)
      {
           Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
      }


      //------------------ read the SERVER RESPONSE


      try {
            inStream = new DataInputStream ( conn.getInputStream() );
            String str;

            while (( str = inStream.readLine()) != null)
            {
                 Log.e("MediaPlayer","Server Response"+str);
            }
            /*while((str = inStream.readLine()) !=null ){

            }*/
            inStream.close();

      }
      catch (IOException ioex){
           Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
      }



    }
}



如果您没有收到任何错误..那么Internet权限不是问题。。
我认为您的URL可能是问题所在。如果您配置了本地主机,即使您无法从移动设备访问该本地主机URL。

检查internet权限?尝试使用MultipartEntity而不是HttpEntity。我已添加了internet权限,但显然仍然没有更改。感谢演示链接,但这是一个不同的场景,因为图像由摄像头捕获,然后直接上传到服务器,而无需将其保存到sd卡。首先尝试简单的图像上传,而不是使用此功能
<uses-permission android:name="android.permission.INTERNET" />