【问题标题】:upload image in android studio在android studio中上传图片
【发布时间】:2020-11-08 23:46:47
【问题描述】:

我正在尝试使用 android-studio 和 php 将图像上传到 xampp 服务器 但我不会成功 请帮帮我

这是我的代码(java 和 php):

java代码: 在这段代码中,我试图从图库中选择图片并显示一个对话框,然后上传图片...

public final int REQUEST_OPEN_GALLERY = 5;
        ProgressDialog dialog;
        Thread uploadThread;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String id = "";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        public static Handler uploadHandler;
        public static String imageProfile = "";
        
        profile_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseFile();
            }
        });

    }
    private void chooseFile() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_OPEN_GALLERY);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_OPEN_GALLERY && resultCode == RESULT_OK && data != null) {
            Uri uri = data.getData();
            String[] info = {MediaStore.Images.Media.DATA};
            Cursor cursor = getActivity().getContentResolver().query(uri, info, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(info[0]);
            final String filePath = cursor.getString(columnIndex);
            //Toast.makeText(MainActivity.this,filePath,Toast.LENGTH_SHORT).show();
            dialog = ProgressDialog.show(getContext(), "upload", "Uploading file...");

            uploadThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadFile(filePath);
                }
            });
            uploadThread.start();

        }
    }
    private void uploadFile(String filePath) {
        File file = new File(filePath);
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            URL url = new URL("http://192.168.1.6/zanborak/sabtenam/upload.php");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file", filePath);

            DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd + "Content-Disposition: form-data;" +
                    " name=\"uploaded_file\";filename=\"" + filePath + "\"\r\n\r\n");
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {

                dataOutputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            dataOutputStream.writeBytes(lineEnd);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        
            if (connection.getResponseCode() == 200) {
                uploadHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        Toast.makeText(getContext(), "Upload Completed", Toast.LENGTH_SHORT).show();
                        imageProfile = "";
                        
                    }
                });

            }

            fileInputStream.close();
            dataOutputStream.flush();
            dataOutputStream.close();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

和php:

在此代码中,我尝试将图像移动到“上传”文件夹...

    <?php
include "connect.php";
$rand=microtime();
$path="upload/".$rand.($_FILES["uploaded_file"]["name"]);
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],$path);
?>

【问题讨论】:

    标签: java php android-studio xampp


    【解决方案1】:

    如果你使用Retrofit 库会更好。它是一个通过 Http 协议交换数据和媒体并等待响应的轻量级库。

    您可以在official website 中查看如何将其添加为依赖项。

    您还需要在您的 gradle 中添加 Gson serializer 依赖项。

    一旦完成创建负责获取改造对象:

    public class RetrofitApiClient {
    
        private static final String BASE_URL = "http://192.168.1.6/"; //htt
    
        private static Retrofit retrofit = null;
    
        private static Gson gson = new GsonBuilder()
                .serializeNulls()
                .setLenient()
                .create();
    
        private RetrofitApiClient() {} // So that nobody can create an object with constructor
    
        public static synchronized Retrofit getClient() {
            if (retrofit==null) {
                int timeOut = 5 * 60;
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(timeOut, TimeUnit.SECONDS)
                        .writeTimeout(timeOut, TimeUnit.SECONDS)
                        .readTimeout(timeOut, TimeUnit.SECONDS)
                        .build();
    
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(ScalarsConverterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(client)
                        .build();
            }
            return retrofit;
        }
    }
    

    Retrofit 将您的 HTTP API 转换为 Java 接口,因此创建一个接口来处理上传的 url

    public interface FileService {
    
        @Multipart
        @POST("/zanborak/sabtenam/upload.php")
        Call<String> UploadImage( 
                @Part MultipartBody.Part file);
    }
    

    现在您可以创建一个类来负责将您的文件推送到服务器并等待响应。

    public class ImageUploaderClass {
    
        //listerner for the task
        public interface OnSuccessfullTask {
            void onSuccess();
            void onFailed(String error);
        }
    
        public static void uploadImage(String filePath,  OnSuccessfullTask task) {
            try {
                FileService apiInterface = RetrofitApiClient.getClient().create( FileService .class);
    
                File file = new File(filePath);
                //create RequestBody instance from file
                RequestBody requestFile = RequestBody.create(MediaType.parse("image"), file);
    
                // MultipartBody.Part is used to send also the actual file name
                MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", file.getName(), requestFile);
    
                // finally, execute the request
                Call<String> call = apiInterface.UploadImage(body);
                call.enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                        String responseBody = response.body();
                        if (responseBody != null) {
                            if ("ok".equals(responseBody)) {
                                task.onSuccess();
                            } else { 
                                task.onFailed(responseBody);
                            }
                        } else { 
                            task.onFailed(responseBody);
                        }
                    }
    
                    @Override
                    public void onFailure(@NotNull Call<String> call, @NotNull Throwable t) {
                        task.onFailed(t.getMessage());
                    }
    
                });
            }
            catch (Exception ignored){}
        }
    
    }
    

    在你的 PHP 中返回一些东西给应用程序以防成功或失败

    <?php
    include "connect.php";
    $rand=microtime();
    $path="upload/".$rand.($_FILES["uploaded_file"]["name"]);
    $r = move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],$path);
    if($r){
    echo 'ok';
    }
    else{
    echo 'error';
    }
    ?>
    

    最后,您可以在 ActivityResult 中调用 uploadImage 并将文件名和成功或失败所需的操作传递给它

    【讨论】:

      猜你喜欢
      • 2017-04-15
      • 2016-09-26
      • 2017-06-13
      • 1970-01-01
      • 2012-05-20
      • 2012-03-07
      • 2012-01-25
      • 2022-11-23
      • 1970-01-01
      相关资源
      最近更新 更多