PHP的Andr​​oid上传失败 [英] PHP Android upload failed

查看:157
本文介绍了PHP的Andr​​oid上传失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用hosting24.com为PHP文件上传的实施和将要上传的MP4文件。用于测试的HTML文件,它workds。当它由Android deivces来执行,它失败并显示$名称= $ _FILES [uploaded_file]为空。请你告诉我,有没有其他的因素$ P $从上传成功pventing我们吗?

以下是我的code

 公共字符串uploadFIle(档案文件){
        字符串结果=;        HttpURLConnection的康恩= NULL;
        DataOutputStream类DOS = NULL;
        字符串lineEnd =\\ r \\ n;
        串twoHyphens = - ;
        字符串边界=*****;
        字符串文件名= file.getName();
        INT读取动作,方bytesAvailable,缓冲区大小;
        INT serverResponse code = 0;
        字节[]缓冲区;
        INT MAXBUFFERSIZE = 1 * 1024 * 1024;        的FileInputStream的FileInputStream;
        尝试{
            的FileInputStream =新的FileInputStream(文件);
            网址URL =新的URL(http://www.gallicalab.com/upload.php);            //打开HTTP连接的URL
            康恩=(HttpURLConnection类)url.openConnection();
            conn.setDoInput(真); //允许输入
            conn.setDoOutput(真); //允许输出
            conn.setUseCaches(假); //不要使用缓存副本
            conn.setRequestMethod(POST);
            conn.setRequestProperty(连接,保持活动);
            conn.setRequestProperty(ENCTYPE,多部分/表单数据);
            conn.setRequestProperty(内容类型,的multipart / form-data的;边界=+边界);
            conn.setRequestProperty(uploaded_file,文件名);            DOS =新的DataOutputStream类(conn.getOutputStream());            dos.writeBytes(twoHyphens +边界+ lineEnd);
            dos.writeBytes(内容处置:表格数据;名称= \\uploaded_file \\;文件名=
                    +文件名+\\+ lineEnd);                    dos.writeBytes(lineEnd);            //创建最大大小的缓冲区
            参考bytesAvailable = fileInputStream.available();            BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
            缓冲区=新的字节[缓冲区大小]            //读取文件,并将其写入形式...
            读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);            而(读取动作大于0){                dos.write(缓冲液,0,缓冲区大小);
                参考bytesAvailable = fileInputStream.available();
                BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
                读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);            }            //发送文件数据后necesssary多部分的表单数据...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);            //服务器的响应(code和消息)
            serverResponse code = conn.getResponse code();
            InputStream为= conn.getInputStream();            如果(serverResponse code == 200){
                读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是,UTF-8),8192);
                StringBuilder的SB =新的StringBuilder();
                串线= NULL;
                而((行= reader.readLine())!= NULL){
                    sb.append(线);
                }
                结果= sb.toString();
            }        //结果= serverResponseMessage;
        }赶上(FileNotFoundException异常五){
            // TODO自动生成catch块
            e.printStackTrace();
        }赶上(MalformedURLException的E){
            // TODO自动生成catch块
            e.printStackTrace();
        }赶上(的ProtocolException E){
            // TODO自动生成catch块
            e.printStackTrace();
        }赶上(IOException异常五){
            // TODO自动生成catch块
            e.printStackTrace();
        }
        返回结果;
    }

服务器端

 < PHP
使用error_reporting(E_ALL);    $ target_path =目标/;
  // $ target_path = $ target_path。基本名($ _FILES ['文件'] ['名']);
    $ NAME = $ _FILES [uploaded_file] [名称];
  //回声$名称。< BR>中;
    $ EXT =结束(爆炸(,$名)。);
    //回声$分机< BR>中。
    $ randname = random_string(30);
   //回声$ randname< BR>中。
    $ FNAME = $ randname。 。 。$ EXT;
    //回声$ FNAME< BR>中。
    $ target_path = $ target_path $ FNAME。
   //回声$ target_path< BR>中。
    如果(move_uploaded_file($ _ FILES ['uploaded_file'] ['tmp_name的值'],$ target_path)){
        //回声文件。 。基本名($ _FILES ['文件'] ['名'])已上传;
        //回声random_string(50);        // $ ARR =阵列('数据'=>的http://gallicalab.com/target/'.$_FILES ['文件'] ['名']);
        $ ARR =阵列('数据'=>的http://gallicalab.com/target/'.$fname);        回声json_en code($ ARR); // {一:1,B:2,C:3,D:4,e的:5}
    }
    其他{
        回声发生错误上传文件,请重试!
    }    功能random_string($长度){
    $关键='';
    $键= array_merge(范围(0,9),范围('一个','Z'));    为($ I = 0; $ I< $长度; $ I ++){
        $键= $键[array_rand($键)。
    }    返回$关键;
    }?>


解决方案

你能登入你实际上是什么样接收在服务器端的文件? Android应用程序可能无法正确​​地提出请求。

试试这个:

 < PHP
使用error_reporting(E_ALL);$ H =的fopen('upload.log','W');
FWRITE($ H,的print_r($ _ POST,真)为\\ r \\ n --- \\ r \\ n);
FWRITE($ H,的print_r($ _ FILES,真实));
FCLOSE($ H);//你的code休息

然后检查 upload.log 文件看看从设备您的要求发生了什么。


P.S。试试这个替代上传code为Android:

 私人无效uploadFile(字符串文件路径,字符串文件名){
  InputStream的InputStream的;
  尝试{
    的InputStream =新的FileInputStream(新文件(文件路径));
    字节[]数据;
    尝试{
      数据= IOUtils.toByteArray(InputStream的);      HttpClient的HttpClient的=新DefaultHttpClient();
      HttpPost httpPost =新HttpPost(http://www.gallicalab.com/upload.php);      InputStreamBody inputStreamBody =新InputStreamBody(新ByteArrayInputStream的(数据),文件名);
      MultipartEntity multipartEntity =新MultipartEntity();
      multipartEntity.addPart(文件,inputStreamBody);
      httpPost.setEntity(multipartEntity);      HTT presponse HTT presponse = httpClient.execute(httpPost);      //处理响应从脚本回来。
      如果(HTT presponse!= NULL){      }其他{//错误,没有任何反应。      }
    }赶上(IOException异常五){
      e.printStackTrace();
    }
  }赶上(FileNotFoundException异常E1){
    e1.printStackTrace();
  }
}

在服务器端:

  $ OBJFILE =安培; $ _FILES [文件];
$ strPath的基本名称=($ OBJFILE [名称]);如果(move_uploaded_file($ OBJFILE [tmp_name的值],$ strPath中)){
    打印文件。 $ strPath的。 已上传。
}其他{
    打印有错误上传文件,请重试!
}

来源:的http://www.$c$cpuppet.com/2013/03/26/android-uploading-a-file-to-a-php-server/

I am currently using hosting24.com for php file upload implementation and going to upload mp4 files. The html file for testing , it workds. When it comes to the execution by Android deivces , it fails and shows the $name = $_FILES["uploaded_file"] is null. Would you please tell me is there any other factors preventing us from successful upload ?

The below is my code

public String uploadFIle(File file){
        String result = "";

        HttpURLConnection conn = null;
        DataOutputStream dos = null;  
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String fileName =  file.getName();
        int bytesRead, bytesAvailable, bufferSize;
        int serverResponseCode = 0;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024; 

        FileInputStream fileInputStream;
        try {
            fileInputStream = new FileInputStream(file);
            URL url = new URL("http://www.gallicalab.com/upload.php");

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection(); 
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName); 

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

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

                    dos.writeBytes(lineEnd);

            // create a buffer of  maximum size
            bytesAvailable = fileInputStream.available(); 

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

            // read file and write it into form...
            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);   

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            InputStream is = conn.getInputStream();

            if(serverResponseCode==200){
                BufferedReader reader = new BufferedReader(new InputStreamReader(    is, "utf-8"), 8192);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                result =   sb.toString();  
            }



        //  result = serverResponseMessage;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return result;
    }

Server side

<?php
error_reporting(E_ALL);

    $target_path  = "target/";
  //  $target_path = $target_path . basename( $_FILES['file']['name']);
    $name = $_FILES["uploaded_file"]["name"];
  //  echo $name."<br>";
    $ext = end(explode(".", $name));
    //    echo $ext."<br>";
    $randname = random_string(30);
   // echo $randname."<br>";
    $fname = $randname . "." .$ext;
    //echo $fname."<br>";
    $target_path = $target_path .$fname;
   // echo $target_path."<br>";
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) {
        //echo "The file ".  basename( $_FILES['file']['name'])." has been uploaded";
        //echo random_string(50);



        // $arr = array ('data'=>'http://gallicalab.com/target/'.$_FILES['file']['name']);
        $arr = array ('data'=>'http://gallicalab.com/target/'.$fname);

        echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
    } 
    else {
        echo "There was an error uploading the file, please try again!";
    }



    function random_string($length) {
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));

    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }

    return $key;
    }

?>

解决方案

Could you log what you are actually receiving at the server side to a file? Android app might not be making the request correctly.

Try this:

<?php
error_reporting(E_ALL);

$h = fopen('upload.log', 'w');
fwrite($h, print_r($_POST, true) ."\r\n---\r\n");
fwrite($h, print_r($_FILES, true));
fclose($h);

// rest of your code

Then inspect the upload.log file and see what happened with your request from device.


P.S. Try this alternate upload code for android:

private void uploadFile(String filePath, String fileName) {
  InputStream inputStream;
  try {
    inputStream = new FileInputStream(new File(filePath));
    byte[] data;
    try {
      data = IOUtils.toByteArray(inputStream);

      HttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost("http://www.gallicalab.com/upload.php");

      InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
      MultipartEntity multipartEntity = new MultipartEntity();
      multipartEntity.addPart("file", inputStreamBody);
      httpPost.setEntity(multipartEntity);

      HttpResponse httpResponse = httpClient.execute(httpPost);

      // Handle response back from script.
      if(httpResponse != null) {

      } else { // Error, no response.

      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  } catch (FileNotFoundException e1) {
    e1.printStackTrace();
  }
}

At server side:

$objFile = & $_FILES["file"];
$strPath = basename( $objFile["name"] );

if( move_uploaded_file( $objFile["tmp_name"], $strPath ) ) {
    print "The file " .  $strPath . " has been uploaded.";
} else {
    print "There was an error uploading the file, please try again!";
}

Source: http://www.codepuppet.com/2013/03/26/android-uploading-a-file-to-a-php-server/

这篇关于PHP的Andr​​oid上传失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆