1
我試圖將視頻上傳到本地主機上的PHP服務器。我已成功上傳圖片和文本文件,但相同的代碼不適用於視頻。請告訴我這段代碼有什麼問題。上傳視頻不能在Android上傳圖片和文本文件時工作
這裏是服務器端腳本:
<?php
$mysql_host = "localhost";
$mysql_database = "test";
$mysql_user = "root";
$mysql_password = "";
$con = mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database) or die("Unable to select database");
$target_path = "uploads/";
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
echo $target_path;
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename($_FILES['uploadedfile']['name']).
" has been uploaded";
$sql="insert into images set url='$target_path'";
mysql_query($sql);
} else{
echo "There was an error uploading the file, please try again!";
}
?>
這裏是客戶端代碼:
package com.example.imageupload;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
int REQ_CODE_PICK_IMAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
// Bitmap yourSelectedImage =
// BitmapFactory.decodeFile(filePath);
new UploadFile().execute(filePath);
}
}
}
private class UploadFile extends AsyncTask<String, Void, Void> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Log.d("start", "start");
}
@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
//String pathToOurFile="/mnt/sdcard/code.txt";
String pathToOurFile = params[0];
Log.d("start", params[0]);
String urlServer = "http://10.0.2.2/uploadfile.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String response ;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(
new File(pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// 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);
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
Log.d("BuffrerReader", "" + in);
if (in != null) {
response = convertStreamToString(in);
Log.e("FINAL_RESPONSE-LENGTH",""+response.length());
Log.e("FINAL_RESPONSE", response);
}
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection
.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
// Exception handling
}
} catch (Exception ex) {
ex.printStackTrace();
}
return (null);
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("end", "end");
}
}
public String convertStreamToString(BufferedReader is)
throws IOException {
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = is.readLine()) != null) {
sb.append(line).append("");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
}
你是否收到任何錯誤信息? – fmodos
「上傳文件時出錯,請重試!」上傳視頻時出現這條消息 –
這是'php'問題,因爲'move_uploaded_file($ _ FILES ['uploadedfile'] ['tmp_name'],$ target_path' returns false。您應該檢查服務器端的日誌,看看那裏出了什麼問題 – gunar