java - 在 Android 中上传图像和文本文件时上传视频不起作用

标签 java php android

我正在尝试将视频上传到本地主机上的 PHP 服务器。我已成功上传图片和文本文件,但相同的代码不适用于视频。请告诉我这段代码有什么问题。

这是服务器端脚本:

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

最佳答案

更改 php.ini 中的 upload_max_filesize 的值,默认为 2M 到所需的限制

关于java - 在 Android 中上传图像和文本文件时上传视频不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17586654/

相关文章:

javascript - 如何在模态中传递 php 值? Bootstrap 3,

php - 在 WordPress 中比较散列密码与 PHP

java - 在java中拆分字符串作为分隔符

javascript - 不显示来自 Phonegap 的联系人图像

android - 从 Android 应用程序中的 busybox 命令获取输出

java - Redis hmget 超时时间

java - IntelliJ cucumber .ClassNotFoundException

php - 如何将缩略图存储到数据库中?

java - 将@Nullable 放在具有可为空返回类型的方法的何处?

java - Quickblox 中的 NullPointerException