【问题标题】:Uploading data via a post method to a server Android Studio通过 post 方法将数据上传到服务器 Android Studio
【发布时间】:2020-11-07 08:55:30
【问题描述】:

我正在尝试通过 android studio 中的 POST 请求将图像上传到服务器,但我完全卡住了。控制台没有给我任何可能表明出了什么问题的信息,当我点击上传时它就不起作用了。

代码如下:

public class UploadActivity extends AppCompatActivity implements View.OnClickListener {
ImageView imageToUpload;
Button uploadButton;
EditText imageNameText;
ImageButton backButton;
private static final int RESULT_LOAD_IMAGE=1;
private static final String SERVER_ADDESS = "http://lukertestsite.000webhostapp.com/";      // address of my free 000webhost domain


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.upload_page);

    imageToUpload = (ImageView)findViewById(R.id.imageToUpload);
    uploadButton = (Button)findViewById(R.id.uploadImageButton);
    imageNameText = (EditText)findViewById(R.id.imageName);
    backButton = (ImageButton)findViewById(R.id.returnButton);




    // set a listener for each button that will pass this as the view, since this class implements listener
    imageToUpload.setOnClickListener(this);
    uploadButton.setOnClickListener(this);
    backButton.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch(view.getId()){
        case R.id.imageToUpload:
            Intent localImagesIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(localImagesIntent, RESULT_LOAD_IMAGE);

            break;
        case R.id.uploadImageButton:
            Bitmap pic = ((BitmapDrawable) imageToUpload.getDrawable()).getBitmap();        // grab the pic as a bitmap
            new UploadImage(pic,imageNameText.getText().toString()).execute();
            break;

        case R.id.returnButton:

            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == RESULT_LOAD_IMAGE && resultCode==RESULT_OK && data!=null) {        // ensuring the gallery intent is what calls the method, and the result is ok and data is passed i.e. not null
        Uri selectedImage = data.getData();                             // making a uniform result (basically a pointer to the image)
        imageToUpload.setImageURI(selectedImage);           // set the image to upload display to the selected image.
    }
}



// asynch task to commiunicate with server in the background

private class UploadImage extends AsyncTask<Void,Void,Void>{
    Bitmap image;
    String name;


    public UploadImage(Bitmap image, String name){
        this.image=image;
        this.name=name;

    }

    @Override
    protected Void doInBackground(Void... voids) {
        // encode image in base 64
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        image.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream);    // compress as a png into bytearraystream
        String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT);

        ArrayList<NameValuePair> dataToSend = new ArrayList<>();
        dataToSend.add(new BasicNameValuePair("image",encodedImage));
        dataToSend.add(new BasicNameValuePair("name",name));

        HttpParams httpRequestParams = getHttpRequestParams();
        HttpClient client = new DefaultHttpClient(httpRequestParams);
        HttpPost post = new HttpPost(SERVER_ADDESS + "UploadPic.php");

        try{
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
            System.out.println("set post entity");
            client.execute(post);
            System.out.println("executing post");
        }catch (Exception e){
            e.printStackTrace();
        }



        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Toast.makeText(getApplicationContext(),"Your pic was uploaded",Toast.LENGTH_SHORT);     //Toast to alert user their file was uploaded
        System.out.println("toasted");
    }
}

private HttpParams getHttpRequestParams(){

    System.out.println("getting request params");
    HttpParams httpRequestParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpRequestParams,1000*40);
    HttpConnectionParams.setSoTimeout(httpRequestParams,1000*40);

    return httpRequestParams;
}

这是我在控制台中得到的输出。

> Connected to process 13772 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/ample.picloade: The ClassLoaderContext is a special shared library.
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/ample.picloade: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/ample.picloade: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xf0cd5a30, tid 13864
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xf0ae20c0: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xf0ae20c0: ver 2 0 (tinfo 0xf0e1e7f0) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
    HostConnection::get() New Host Connection established 0xf0cd5af0, tid 13864
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3fa2b4000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2 
I/Choreographer: Skipped 122 frames!  The application may be doing too much work on its main thread.
W/ample.picloade: JNI critical lock held for 65.664ms on Thread[1,tid=13772,Runnable,Thread*=0xe2cc4610,peer=0x71ffe018,"main"]
I/AssistStructure: Flattened final assist data: 1464 bytes, containing 1 windows, 9 views
I/System.out: getting request params
I/System.out: set post entity
I/System.out: executing post
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10152; state: ENABLED
I/System.out: toasted

这是代码中使用的 PHP 文件:

<?php 
if(isset($_POST['name'])){ $name = $_POST['name']; }
if(isset($_POST['image'])){ $image = $_POST['image']; }

$decodedImage = base64_decode("$image");
file_put_contents("picbox_pics/" . $name . ".PNG", $decodedImage);

?>

任何想法都将不胜感激,因为我已经被困了一天左右。我认为这可能与“D / CompatibilityChangeReporter:Compat change id报告:147798919;UID 10152;状态:启用”有关,这发生在吐司应该(或至少在我的“吐司”打印之前的一段时间)时,但我无法在模拟器中关闭该选项,我什至不确定这是问题所在。

编辑:这是 php 输出:

Notice: Undefined index: name in /storage/ssd2/037/14360037/public_html/UploadPic.php on line 2

Notice: Undefined index: image in /storage/ssd2/037/14360037/public_html/UploadPic.php on line 3
Here is some more debugging info:Array ( )
Warning: file_put_contents(picbox_pics/.PNG): failed to open stream: No such file or directory in /storage/ssd2/037/14360037/public_html/UploadPic.php on line 9

【问题讨论】:

  • 文件通常到达名为$_FILES的数组中你检查了吗
  • 我是 php 新手,我该如何检查呢?我注意到你可以像这样打印/回显:echo 'the files are:'; print_r($_FILES); 但我不知道输出到哪里?它会以某种方式发送到我的 android studio 终端吗?
  • 哦,没关系,我只需要转到我服务器上的 php 目录。我添加了在帖子中打印 $_FILES 得到的输出。有什么想法吗?和我的安卓模拟器有关系吗?

标签: java php android post upload


【解决方案1】:

您没有在 toast 上调用 show(),这就是它不显示的原因。应该是这样的: Toast.makeText(getApplicationContext(),"你的图片已上传",Toast.LENGTH_SHORT).show();

【讨论】:

  • 哦,哎呀,没注意到哈哈。谢谢,但是 toast 只是实际问题的一个可能症状,即没有任何内容上传到服务器。它只是运行,没有错误,然后完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 2023-04-06
  • 2015-10-05
  • 2016-03-31
相关资源
最近更新 更多