我正试图通过android studio中的POST请求上传一张图片到服务器上,但我完全被困住了。 控制台没有给我任何信息,可以指出出了什么问题,当我单击上传,它只是不工作。 我在postexecute中调用的toast甚至没有显示出来,但是在toast之后我放进去的print显示出来了,所以程序在执行时肯定会显示出来。
代码如下: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{
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 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
$name = $_POST["name"];
$image = $_POST["image"];
$decodedImage = base64_decode("$image");
file_put_contents("picbox_pics/" . $name . ".PNG", $decodedImage);
?>
如果你有任何想法,我会非常感激的,因为我已经被困了一天左右了。 我认为这可能与“d/compatibilitychangeReporter:Compat change id reported:147798919;UID 10152;state:enabled”有关,它恰好发生在吐司应该发生的时候(或者至少在我的“吐司”打印之前的一段时间),但是我不能在模拟器中关闭该选项,我甚至不确定这是问题所在。