php – 改进2在Postman和Localhost中工作但不在亚马逊AWS Live Server上工作

我的改造实例与localhost(包括android代码和邮递员)一起工作正常,并且在邮递员工作正常.但是当我去亚马逊AWS实例(在线a.k.a)时,android部分无效.请参阅下面的代码.来自android的错误日志是D /响应:{“error”:true,“message”:“所需参数不可用”}

有趣的是问题是大文件大小2M,小文件大小24KB正在上传罚款.我已经检查了PHP.ini文件,最大大小有25MB

我正在学习本教程:https://www.simplifiedcoding.net/retrofit-upload-file-tutorial/

public interface Api {

    //the base URL for our API
    //make sure you are not using localhost
    //find the ip usinc ipconfig command
    String BASE_URL = "http://creative-thinker.com/files/images/secret_crushes/";

    //this is our multipart request
    //we have two parameters on is name and other one is description
    @Multipart
    @POST("Api.PHP?apicall=upload")
    Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ")
                                         RequestBody file, @Part("desc") RequestBody desc);

}

我的对象类

public class MyResponse {
    public boolean error;
    String message;
}

我的片段

ivImageView.setonClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        // Open The File Choose And Send To Activity For Result
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, 100);

    }
});

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && data != null) {
            //the image URI
            Uri selectedImage = data.getData();

            //calling the upload file method after choosing the file
            uploadFile(selectedImage, "My Image");
        }
    }

    private void uploadFile(Uri fileUri, String desc) {

        //creating a file
        File file = new File(getRealPathFromURI(fileUri));

        //creating request body for file
        RequestBody requestFile = RequestBody.create(MediaType.parse(getContext().getContentResolver().getType(fileUri)), file);
        RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);

        //The gson builder
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        //creating retrofit object
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();


        //creating our api
        Api api = retrofit.create(Api.class);

        //creating a call and calling the upload image method
        Call<MyResponse> call = api.uploadImage(requestFile, descBody);

        //finally performing the call
        call.enqueue(new Callback<MyResponse>() {
            @Override
            public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
                if (!response.body().error) {
                    Toast.makeText(getContext().getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
                } else {

                    MyResponse res= response.body();
                    Log.d("response", new Gson().toJson(res));
                    Toast.makeText(getContext().getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<MyResponse> call, Throwable t) {
                Toast.makeText(getContext().getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    /*
     * This method is fetching the absolute path of the image file
     * if you want to upload other kind of files like .pdf, .docx
     * you need to make changes on this method only
     * Rest part will be the same
     * */
    private String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader loader = new CursorLoader(getContext(), contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.movetoFirst();
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }

FileHandler.PHP

<?PHP


class FileHandler
{

    private $con;

    public function __construct()
    {
        require_once dirname(__FILE__) . '/DbConnect.PHP';

        $db = new DbConnect();
        $this->con = $db->connect();
    }

    public function saveFile($file, $extension, $desc)
    {
        $name = round(microtime(true) * 1000) . '.' . $extension;
        $filedest = dirname(__FILE__) . UPLOAD_PATH . $name;
        move_uploaded_file($file, $filedest);

        $url = $server_ip = gethostbyname(gethostname());

        $stmt = $this->con->prepare("INSERT INTO images (description, image) VALUES (?, ?)");
        $stmt->bind_param("ss", $desc, $name);
        if ($stmt->execute()) {
            return true;
        }

        return false;
    }

    public function getAllFiles()
    {
        $stmt = $this->con->prepare("SELECT id, description, image FROM images ORDER BY id DESC");
        $stmt->execute();
        $stmt->bind_result($id, $desc, $url);

        $images = array();

        while ($stmt->fetch()) {

            $temp = array();
            $absurl = 'http://' . gethostbyname(gethostname()) . '/files/images/secret_crushes' . UPLOAD_PATH . $url;
            $temp['id'] = $id;
            $temp['desc'] = $desc;
            $temp['url'] = $absurl;
            array_push($images, $temp);
        }

        return $images;
    }

}

Api.PHP

<?PHP


require_once dirname(__FILE__) . '/FileHandler.PHP';

$response = array();

if (isset($_GET['apicall'])) {
    switch ($_GET['apicall']) {
        case 'upload':

            if (isset($_POST['desc']) && strlen($_POST['desc']) > 0 && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $upload = new FileHandler();

                $file = $_FILES['image']['tmp_name'];

                $desc = $_POST['desc'];

                if ($upload->saveFile($file, getFileExtension($_FILES['image']['name']), $desc)) {
                    $response['error'] = false;
                    $response['message'] = 'File Uploaded Successfullly';
                }

            } else {
                $response['error'] = true;
                $response['message'] = 'required parameters are not available';
            }

            break;

        case 'getallimages':

            $upload = new FileHandler();
            $response['error'] = false;
            $response['images'] = $upload->getAllFiles();

            break;
    }
}

echo json_encode($response);

function getFileExtension($file)
{
    $path_parts = pathinfo($file);
    return $path_parts['extension'];
}

我试图捕获Api.PHP中的项目值

$response [‘message’] = $string;只是在哪里$response [‘message’] =’所需参数不可用’;

并获得以下结果

    $string = $_POST['desc'];
    D/response: {"error":true,"message":"My Image"}

    $string = $_POST['desc'];
    $string = strlen($string);
    D/response: {"error":true,"message":"8"}

    $string = $_FILES['image']['error'];
    D/response: {"error":true}

    $string = UPLOAD_ERR_OK;
    D/response: {"error":true,"message":"0"}

删除&& $_FILES [‘image’] [‘error’] === UPLOAD_ERR_OK将数据输入数据库但没有图像仍然上传

解决方法:

最后在搜索网络后找到解决方案…问题是文件大小

我在PHP 7和Apache上.所以配置需要在两个地方改变

配置

upload_max_filesize = 25M
post_max_size = 25M
max_execution_time = 300
max_input_time = 300
memory_limit = 128M

位置

sudo nano /etc/PHP/7.0/fpm/PHP.ini
sudo nano /etc/PHP/7.0/apache2/PHP.ini

显然,需要在Amazon AWS上为PHP和Apache更改设置.希望它能帮助别人.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...