简体   繁体   English

文件从android上传到php服务器不起作用

[英]file upload to php server from android not working

I am trying to upload a mp3 file from my android device(2.3.3) but failing. 我试图从我的android设备(2.3.3)上传mp3文件,但失败。 I have seen lot of similar queries here but could not find any solution for my problem. 我在这里看到过很多类似的查询,但是找不到解决我问题的方法。 I am not very good in php 我的PHP不是很好

Following is my implementation in a service which I am starting from an 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();


}

}

The following permissions are added in the manifest 清单中添加了以下权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

This is my PHP script running at the server: 这是我在服务器上运行的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";   
} 

?>

I am able to connect to the server & the HTTP server is sending message code =200 and message=OK. 我能够连接到服务器,并且HTTP服务器正在发送消息代码= 200和message = OK。 However, the php script is not getting any files. 但是,PHP脚本未获取任何文件。 The function move_uploaded_file() is returning false & hence I am getting value false in my device. 函数move_uploaded_file()返回false,因此我在设备中获取的值为false。 I have tried with variety of file sizes but failing. 我尝试了各种文件大小,但都失败了。

However, I was able to upload a mp3 file to the same php script from my desktop browser. 但是,我可以从桌面浏览器将mp3文件上传到相同的php脚本。 I believe this rules out any possibility of ini file mistakes or security settings issues. 我相信这可以排除ini文件错误或安全设置问题的任何可能性。

Please help me find the solution. 请帮助我找到解决方案。

Thanks in advance 提前致谢

You haven't checked if the upload succeeded: 您尚未检查上传是否成功:

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

The rest of the HTTP process can work perfectly but still have a failed file upload for any number of reasons, so never ever assume the upload succeeded. HTTP进程的其余部分可以正常运行,但是由于多种原因,文件上传仍然失败,因此永远不要认为上传成功。

The error codes are defined here . 错误代码在此处定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM