Android,자바 서버 에 사진 업로드

요 며칠 휴대 전화 사진,앨범 사진 이 서버 에 올 라 오 는 작은 사례 가 있다.클 라 이언 트 와 서버 의 코드 가 모두 붙 어 있 습 니 다.
클 라 이언 트
AndroidManifest.xml 다음 권한 추가

<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"/>

클 라 이언 트 의 업로드 사진 activityupload.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() {
  //             ,         
  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<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     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.java uploadimg.jsp`,lib 라 이브 러 리

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>
실행 결과:
클 라 이언 트

서버

괜 찮 은 것 같 아 요.친구 들 이 하트 를 눌 러 주세요.격려해 주세요!
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기