Загрузить сервер изображений с помощью multipart в Android

Загрузите сервер изображений, используя multipart в Android. Вот я использовал это url

public static final String UPLOAD_URL = "http://abcds.com/clients/cupidapi/uploadimg";

Здесь я использовал составной для загрузки изображения на сервер базы данных Mysql. Когда я пытаюсь загрузить изображение на сервер, на моем устройстве отображается уведомление с надписью «Загрузить успешно», но в базе данных нет загруженной записи изображения.

public void uploadMultipart() {

           //getting the actual path of the image
            String path = getPath(filePath);

            Log.e(TAG,"PATH---------->"+path);
            //Uploading code
            try {
                String uploadId = UUID.randomUUID().toString();

                Log.e(TAG,"UPLOADID-------->"+uploadId);
                //Creating a multi part request
                new MultipartUploadRequest(this, uploadId,UPLOAD_URL)
                        .addFileToUpload( "image",path) //Adding file
                        .addParameter("name", name) //Adding text parameter to the request
                        .setNotificationConfig(new UploadNotificationConfig())
                        .setMaxRetries(2)
                        .startUpload(); //Starting the upload
                Log.e(TAG,"URL----->"+path);

            } catch (Exception exc) {
                Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
                Log.e(TAG,"GETMESSAGE"+exc.getMessage());
            }
        }

содержимое, которое я регистрирую, выглядит так:

03-20 13:42:28.316 12069-12089/com.example.uploadimageserver E/[DRVB][EXT][UTIL]: disp_only_chk: DRVB CHECK DISP PROCESS DONE ! (1/0x2f/0x30/0x2e)
03-20 13:42:28.316 12069-12089/com.example.uploadimageserver E/[DRVB][EXT][UTIL]: disp_only_chk: DRVB CHECK DISP PROCESS DONE ! (0/0/0)
03-20 13:46:44.656 12069-12069/com.example.uploadimageserver E/MainActivity: PATH---------->/storage/emulated/0/Pictures/Instagram/IMG_20190218_082042_666.jpg
03-20 13:46:44.691 12069-12069/com.example.uploadimageserver E/MainActivity: UPLOADID-------->35020ace-11aa-40cc-b0f4-50ec2879b9bd
03-20 13:46:44.745 12069-12069/com.example.uploadimageserver E/MainActivity: URL----->/storage/emulated/0/Pictures/Instagram/IMG_20190218_082042_666.jpg

Вот мой код сервера:

 private function uploadimg(){

                        $currentDir = getcwd();
                        $uploadDirectory = "profile/";
                        $errors = []; // Store all foreseen and unforseen errors here
                        $fileExtensions = ['jpeg','jpg','png','gif']; // Get all the file extensions
                        $userid =$_POST['user_id'];
                        $fileName = $_FILES['images']['name'];
                        $fileSize = $_FILES['images']['size'];
                        $fileTmpName  = $_FILES['images']['tmp_name'];
                        $fileType = $_FILES['images']['type'];
                        $fileExtension = strtolower(end(explode('.',$fileName)));

                        $uploadPath = $currentDir . $uploadDirectory . basename($fileName);
                        $uploadPath =  $uploadDirectory . basename($fileName);

                     $imgurl = "https://abcds.com/clients/cupidapi/".$uploadDirectory.$fileName ;

                        if (isset($_POST['name'])) {

                            if (! in_array($fileExtension,$fileExtensions)) {
                                $errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
                            }

                            if ($fileSize > 2000000) {
                                $errors[] = "This file is more than 2MB. Sorry, it has to be less than or equal to 2MB";
                            }

                            if (empty($errors)) {
                                $didUpload = move_uploaded_file($fileTmpName, $uploadPath);
                                if ($didUpload) {
                                    $success[] = "profile upload successfuly";
                                    $sql  = "INSERT INTO db_images(image_path,user_id) VALUES('$imgurl','$userid')";
                                    $res=mysql_query($sql);  
                                } else {
                                    $errors[] = "An error occurred somewhere. Try again or contact the admin";
                                }
                            } else {
                                foreach ($errors as $error) {
                                    $errors[] = $error . "These are the errors" . "\n";
                                }
                            }
                        }else{
                            $re = "inserting problem....";
                            print(json_encode($re));
                        }



                        if (!$res)
                        {
                            $re = "inserting problem....";
                            print(json_encode($re));

                        }
                        else{
                            $re = "inserting success....";
                            print(json_encode($success));

                        }
            }

Не могли бы вы добавить код вашего сервера? Я также вижу, что вы все ловите, может быть, вы получаете исключение в Java, добавьте также трассировку стека.

Gianluca Benucci 20.03.2019 08:46

Я отредактировал свой код. Пожалуйста, проверьте. @ДжанлукаБенуччи

viral gohil 20.03.2019 09:22

В трассировке стека вы не можете найти ничего похожего на исключение?

Gianluca Benucci 20.03.2019 09:25

НИКОГДА НИКОГДА НЕ ДОВЕРЯЙТЕ ВВОДУ ПОЛЬЗОВАТЕЛЯ $sql = "INSERT INTO db_images(image_path,user_id) VALUES('$imgurl','$userid')"; И еще лучше не добавляйте производственный файл в место, где его все могут видеть..

Gianluca Benucci 20.03.2019 09:26

Нет, я не могу найти никаких исключений @GianlucaBenucci

viral gohil 20.03.2019 09:30
0
5
639
1

Ответы 1

Попробуйте этот пример, это очень хорошо и легко загрузить файл изображения без растянутого изображения.

// Upload File
def uploadServiceVersion = "3.4.2"
implementation "net.gotev:uploadservice:$uploadServiceVersion"

Перейдите на GitHub, затем посмотрите код https://github.com/gotev/android-upload-service/wiki/Setup

Другие вопросы по теме