Android上传图片至java服务器

这几天有做到一个小的案例,手机拍照、相册照片上传到服务器。客户端和服务器的代码都贴出来:

客户端
AndroidManifest.xml添加以下权限

name="android.permission.INTERNET"/>
name="android.permission.CAMERA"/>
name="android.permission.WRITE_EXTERNAL_STORAGE" />
name="android.permission.READ_EXTERNAL_STORAGE"/>

客户端的上传图片activity_upload.xml布局文件


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="300dp"/>

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:layout_margin="16dp"
        android:background="@drawable/edit_text_bg"/>

    <Button
        android:id="@+id/choose_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="选择图片"/>

    <Button
        android:id="@+id/upload_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="上传图片"/>

LinearLayout>

UploadActivity.java界面代码

package com.eric.uploadimage;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.ByteArrayOutputStream;
import cz.msebera.android.httpclient.Header;

@SuppressLint("NewApi")
public class UploadActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editTextName;
    private ProgressDialog prgDialog;

    private int RESULT_LOAD_IMG = 1;
    private RequestParams params = new RequestParams();
    private String encodedString;
    private Bitmap bitmap;
    private String imgPath;


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

        prgDialog= new ProgressDialog(this);
        prgDialog.setCancelable(false);

        editTextName = (EditText) findViewById(R.id.editText);
        findViewById(R.id.choose_image).setOnClickListener(this);
        findViewById(R.id.upload_image).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.choose_image:
                loadImage();
                break;
            case R.id.upload_image:
                uploadImage();
                break;
        }
    }

    public void loadImage() {
     //这里就写了从相册中选择图片,相机拍照的就略过了
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }

    //当图片被选中的返回结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {

                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                // 获取游标
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgPath = cursor.getString(columnIndex);
                cursor.close();
                ImageView imgView = (ImageView) findViewById(R.id.imageView);
                imgView.setImageBitmap(BitmapFactory.decodeFile(imgPath)); 
            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
        }
    }

    //开始上传图片
    private void uploadImage() {
        if (imgPath != null && !imgPath.isEmpty()) {
            prgDialog.setMessage("Converting Image to Binary Data");
            prgDialog.show();
            encodeImagetoString();
        } else {
            Toast.makeText(getApplicationContext(), "You must select image from gallery before you try to upload",
                    Toast.LENGTH_LONG).show();
        }
    }


    public void encodeImagetoString() {
        new AsyncTask() {

            protected void onPreExecute() {

            };

            @Override
            protected String doInBackground(Void... params) {
                BitmapFactory.Options options = null;
                options = new BitmapFactory.Options();
                options.inSampleSize = 3;
                bitmap = BitmapFactory.decodeFile(imgPath,
                        options);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                // 压缩图片
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
                byte[] byte_arr = stream.toByteArray();
                // Base64图片转码为String
                encodedString = Base64.encodeToString(byte_arr, 0);
                return "";
            }

            @Override
            protected void onPostExecute(String msg) {
                prgDialog.setMessage("Calling Upload");
                // 将转换后的图片添加到上传的参数中
                params.put("image", encodedString);
                params.put("filename", editTextName.getText().toString());
                // 上传图片
                imageUpload();
            }
        }.execute(null, null, null);
    }

    public void imageUpload() {
        prgDialog.setMessage("Invoking JSP");
        String url = "http://172.18.2.73:8080/upload/uploadimg.jsp";
        AsyncHttpClient client = new AsyncHttpClient();
        client.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
                prgDialog.hide();
                Toast.makeText(getApplicationContext(), "upload success", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) {
                prgDialog.hide();
                if (statusCode == 404) {
                    Toast.makeText(getApplicationContext(),
                            "Requested resource not found", Toast.LENGTH_LONG).show();
                }
                // 当 Http 响应码'500'
                else if (statusCode == 500) {
                    Toast.makeText(getApplicationContext(),
                            "Something went wrong at server end", Toast.LENGTH_LONG).show();
                }
                // 当 Http 响应码 404, 500
                else {
                    Toast.makeText(
                            getApplicationContext(), "Error Occured n Most Common Error: n1. Device " +
                                    "not connected to Internetn2. Web App is not deployed in App servern3." +
                                    " App server is not runningn HTTP Status code : "
                                    + statusCode, Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (prgDialog  != null) {
            prgDialog .dismiss();
        }
    }
}

服务端
这里用是Intellij Idea 2016.3.1+Tomcat 搭建的本地服务器,前篇文章有介绍具体的搭建步骤。
服务端项目结构:UploadImage.javauploadimg.jsp`、lib库

Android上传图片至java服务器_第1张图片

UploadImage.java

public class UploadImage {

    public static void convertStringtoImage(String encodedImageStr, String fileName) {

        try {
            // Base64解码图片
            byte[] imageByteArray = Base64.decodeBase64(encodedImageStr);

            //
            FileOutputStream imageOutFile = new FileOutputStream("D:/uploads/" + fileName+".jpg");
            imageOutFile.write(imageByteArray);

            imageOutFile.close();

            System.out.println("Image Successfully Stored");
        } catch (FileNotFoundException fnfe) {
            System.out.println("Image Path not found" + fnfe);
        } catch (IOException ioe) {
            System.out.println("Exception while converting the Image " + ioe);
        }
    }
}

uploadimg.jsp 文件

<%@page import="com.eric.UploadImage"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图片上传title>
head>
<body>
<%
    String imgEncodedStr = request.getParameter("image");
    String fileName = request.getParameter("filename");
    System.out.println("Filename: "+ fileName);
    if(imgEncodedStr != null){
        UploadImage.convertStringtoImage(imgEncodedStr, fileName);
        out.print("Image upload complete, Please check your directory");
    } else{
        out.print("Image is empty");
    }
%>
body>
html>

运行结果:

客户端

Android上传图片至java服务器_第2张图片

服务端

Android上传图片至java服务器_第3张图片

觉得还不错的小伙伴们点个赞,鼓励一下!

你可能感兴趣的:(android开发,java)