2014-01-16 85 views
0

我目前使用hosting24.com进行php文件上传实现并上传mp4文件。测试的html文件,它工作。当涉及到Android deivces的执行时,它失败并显示$ name = $ _FILES [“uploaded_file”]为空。您能否告诉我是否有其他因素阻止我们成功上传?PHP Android上传失败

下面是我的代码

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; 
    } 

服务器端

<?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; 
    } 

?> 
+0

也许是这样的:http://stackoverflow.com/questions/18442021/android - 发送文件到服务器php-receive-that-file-in-server – Hackerman

回答

1

你可以登录你实际上是接受什么在服务器端文件? Android应用可能不会正确提出请求。

试试这个:

<?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 

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


P.S.尝试使用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(); 
    } 
} 

在服务器端:

$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!"; 
} 

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

+0

Array ( ) --- Array ( ) 它仍然是空的,甚至使用你的方法 –

+0

,我使用hosting24.com –

+0

我还张贴了这个问题.... http://stackoverflow.com/questions/21162665/android-apache-multipart -php上传-取消定义指数式文件线-6#comment31863724_21162665 –