douyanqu9722 2013-07-11 06:40
浏览 98
已采纳

在Android上传图像和文本文件时上传视频无法正常工作

I am trying to upload a video to a PHP server on localhost. I have successfully uploaded images and text files but the same code does not work for videos. Please tell me what's wrong with this code.

Here is server side script:

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

Here is client side code:

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

}

  • 写回答

1条回答 默认 最新

  • doushi5913 2013-07-11 08:12
    关注

    change the value of upload_max_filesize in php.ini which is by default 2M to desired limit

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存