這幾天有做到一個(gè)小的案例,手機(jī)拍照、相冊(cè)照片上傳到服務(wù)器。客戶端和服務(wù)器的代碼都貼出來(lái):
客戶端
AndroidManifest.xml添加以下權(quán)限
<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.CAMERA"/><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
客戶端的上傳圖片activity_upload.xml布局文件
<?xml version="1.0" encoding="utf-8"?><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() { //這里就寫(xiě)了從相冊(cè)中選擇圖片,相機(jī)拍照的就略過(guò)了 Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(galleryIntent, RESULT_LOAD_IMG); } //當(dāng)圖片被選中的返回結(jié)果 @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 }; // 獲取游標(biāo) 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(); } } //開(kāi)始上傳圖片 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<Void, Void, String>() { 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圖片轉(zhuǎn)碼為String encodedString = Base64.encodeToString(byte_arr, 0); return ""; } @Override protected void onPostExecute(String msg) { prgDialog.setMessage("Calling Upload"); // 將轉(zhuǎn)換后的圖片添加到上傳的參數(shù)中 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(); } // 當(dāng) Http 響應(yīng)碼'500' else if (statusCode == 500) { Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show(); } // 當(dāng) Http 響應(yīng)碼 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(); } }}
服務(wù)端
這里用是Intellij Idea 2016.3.1+Tomcat 搭建的本地服務(wù)器,前篇文章有介紹具體的搭建步驟。
服務(wù)端項(xiàng)目結(jié)構(gòu):UploadImage.javauploadimg.jsp`、lib庫(kù)
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>
運(yùn)行結(jié)果:
客戶端
服務(wù)端
覺(jué)得還不錯(cuò)的小伙伴們點(diǎn)個(gè)贊,鼓勵(lì)一下!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注