从android无法正常上传到php服务器的文件

时间:2012-04-13 19:18:39

标签: php android http

我正在尝试从我的Android设备上传一个mp3文件(2.3.3)但是失败了。我在这里看到了很多类似的查询,但找不到任何解决方案。我不是很擅长php

以下是我在服务中的实现,我从一个Activity

开始
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class SendFileService extends IntentService {
private boolean mFileSent = false;

public SendFileService() {
    super("SendFileService");

}

@Override
protected void onHandleIntent(Intent arg0)
{
    if(arg0 != null)
    {
        final String path = arg0.getStringExtra("path");
        if(path != null & path.length() > 0)
        {
            Thread t = new Thread()
            {
                public void run()
                {
                    try
                    {
                        sendFilewithHTTP(path);
                        while(mFileSent == false)
                        {
                            Thread.sleep(1000 * 60 * 10);// 10 minutes
                            sendFilewithHTTP(path);
                        }   

                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        }
    }
}

@Override
public void onDestroy()
{
    mFileSent = true;
    super.onDestroy();
}

private void sendFilewithHTTP(String filePath)
{
    //Set a global flag to check
    SharedPreferences settings = getSharedPreferences("INFO", MODE_PRIVATE);

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inStream = null;
    if(filePath == null || filePath.length() <3)
    {
        mFileSent = true;
        return;
    }

    String pathToOurFile = filePath;
    String urlServer = "https://www.xxxx.xx/xxx/xxxxxxxx/xxxxxx.php?lang=en&val=" + settings.getString("val", getString(R.string.VAL));
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;

    FileInputStream fileInputStream = null;

    try
    {
        fileInputStream = new FileInputStream(new File(pathToOurFile) );

        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();
        Log.i("Connecting to: ", urlServer);

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

        outputStream = new DataOutputStream( connection.getOutputStream() );
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
        outputStream.writeBytes(lineEnd);

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

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

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

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

        // Responses from the server (code and message)
        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();
        Log.i("File sent to: " + filePath, "Code: " + serverResponseCode + " Message: " + serverResponseMessage);

        mFileSent = true;
        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
        //connection.disconnect();
        }
        catch (Exception ex)
        {
            Log.i("File sent status ", "Connection Failed");
            ex.printStackTrace();
            try
            {
                if(fileInputStream != null)
                    fileInputStream.close();
                if(connection != null)
                    connection.disconnect();
                if(outputStream != null)
                {
                    outputStream.flush();
                    outputStream.close();
                }

            }
            catch(Exception e)
            {

            }
        }

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

            while (( str = inStream.readLine()) != null)
            {
                Log.d("Server response: ", str);
            }
            inStream.close();

      }
      catch (IOException ioex){

      }

      if(connection != null)
        connection.disconnect();


}

}

清单

中添加了以下权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

这是我在服务器上运行的PHP脚本:         

    //check if we have a language and val
    $lang=$_GET['lang'];
    $val=$_GET['val'];

if ( (!isset($val)) || (!isset($lang)) ) die('false');
if ( ($val="") || ($lang="") ) die('false');


//get the file
$fn="data/mydata-".uniqid()."-". date("YmdHis") . ".mp3";

if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $fn)) 
{
    die('false: There was no file in the post request');
}


//check if it's am MP3
$mp3_mimes = array('audio/mpeg3', 'audio/x-mpeg-3', 'audio/mpeg'); 
if (!in_array(mime_content_type($fn), $mp3_mimes)) {
  echo "false: Content type not MP3";
    unlink($fn);        

} else 
{

    //now let's check the file size:
    if (filesize($fn)<(1024*1024*10))
    {
        //Do Something      
    }
    else echo "false: File size too big";   
} 

?>

我可以连接到服务器&amp; HTTP服务器正在发送消息代码= 200和消息=确定。但是,php脚本没有获取任何文件。函数move_uploaded_file()返回false&amp;因此我的设备中的价值是假的。我尝试了各种文件大小但是失败了。

但是,我能够从桌面浏览器上传一个mp3文件到同一个php脚本。 我相信这排除了ini文件错误或安全设置问题的任何可能性。

请帮我找到解决方案。

提前致谢

1 个答案:

答案 0 :(得分:1)

您尚未检查上传是否成功:

if ($_FILES['userfile']['error'] !== UPLOAD_ERR_OK) {
   die("Upload failed with error code " . $_FILES['userfile']['error']);
}

HTTP进程的其余部分可以完美地工作,但由于各种原因仍然无法上传文件,因此永远不要假设上传成功。

错误代码为defined here