我正在尝试从我的 android 设备(2.3.3)上传一个 mp3 文件,但失败了。我在这里看到了很多类似的查询,但找不到任何解决我的问题的方法。我不是很擅长 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";
}
?>
我能够连接到服务器并且 HTTP 服务器正在发送消息代码 = 200 和消息 = OK。但是,php 脚本没有获取任何文件。函数 move_uploaded_file() 返回 false ,因此我的设备中的值 false 。我尝试过各种文件大小但失败了。
但是,我能够从我的桌面浏览器将 mp3 文件上传到相同的 php 脚本。我相信这排除了任何 ini 文件错误或安全设置问题的可能性。
请帮我找到解决方案。
提前致谢