繁体   English   中英

通过 post 方法将数据上传到服务器 Android Studio

[英]Uploading data via a post method to a server Android Studio

我正在尝试通过 android 工作室中的 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;
}

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

> 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 更改 id 报告:147798919;UID 10152;state:ENABLED”有关,这发生在吐司应该(或至少在我的“烤”打印之前的一段时间)时,但我无法在模拟器中关闭该选项,我什至不确定这是问题所在。

编辑:继承人 php output:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM