android code

서버에 이미지 업로드 하는 예제

paulaner80 2016. 7. 29. 19:09
반응형


서버에 이미지 업로드 하는 예제 입니다.

멀티파트로 업로드 합니다.

andorid의 네트워크 라이브러리는 Retrofit2를 사용합니다.


1.Server

1.1 테스트 페이지

<html>

<head>

<title>File Uploading Form</title>

</head>

<body>

<h3>File Upload:</h3>

Select a file to upload: <br />

<form action="imageUpload.jsp" method="post"

                        enctype="multipart/form-data">

<input type="file" name="fileeeee" size="50" />

<br />

<input type="submit" value="Upload File" />

</form>

</body>

</html>


1.2 업로드

<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>

<%@ page import="javax.servlet.http.*" %>

<%@ page import="org.apache.commons.fileupload.*" %>

<%@ page import="org.apache.commons.fileupload.disk.*" %>

<%@ page import="org.apache.commons.fileupload.servlet.*" %>

<%@ page import="org.apache.commons.io.output.*" %>


<%

   File file ;

   int maxFileSize = 5000 * 1024;

   int maxMemSize = 5000 * 1024;

   ServletContext context = pageContext.getServletContext();

   //String filePath = context.getInitParameter("file-upload");

String filePath = config.getServletContext().getRealPath("/upload/");   

System.out.println("realPath :"+filePath);

File temporaryDir = new File(config.getServletContext().getRealPath("/temp/"));

System.out.println("temporaryDir :"+temporaryDir);


   // Verify the content type

   String contentType = request.getContentType();

   if (contentType!=null && (contentType.indexOf("multipart/form-data") >= 0)) {


      DiskFileItemFactory factory = new DiskFileItemFactory();

      // maximum size that will be stored in memory

      factory.setSizeThreshold(maxMemSize);

      // Location to save data that is larger than maxMemSize.

      //factory.setRepository(new File("c:\\temp"));

      factory.setRepository(temporaryDir);


      // Create a new file upload handler

      ServletFileUpload upload = new ServletFileUpload(factory);

      // maximum file size to be uploaded.

      upload.setSizeMax( maxFileSize );

      try

         // Parse the request to get file items.

         List fileItems = upload.parseRequest(request);

         

         System.out.println("fileItems.size() :"+fileItems.size());


         // Process the uploaded file items

         Iterator i = fileItems.iterator();


         out.println("<html>");

         out.println("<head>");

         out.println("<title>JSP File upload</title>");  

         out.println("</head>");

         out.println("<body>");

         while ( i.hasNext () ) 

         {

         System.out.println("aaaaaaaaaaaa");

            FileItem fi = (FileItem)i.next();

            if ( !fi.isFormField () ){

            // Get the uploaded file parameters

            String fieldName = fi.getFieldName();

            System.out.println("@@  fieldName : "+fieldName);

            String fileName = fi.getName();

            boolean isInMemory = fi.isInMemory();

            long sizeInBytes = fi.getSize();

            

            // Write the file

            if( fileName.lastIndexOf("\\") >= 0 ){

            System.out.println("111111111");

            file = new File( filePath + 

            fileName.substring( fileName.lastIndexOf("\\"))) ;

            }else{

            file = new File( filePath + 

            fileName.substring(fileName.lastIndexOf("\\")+1)) ;

            }

            fi.write( file ) ;

            out.println("Uploaded Filename: " + filePath + 

            fileName + "<br>");

            }else{

            System.out.println("bbbbbbb");

            }

         }

         out.println("</body>");

         out.println("</html>");

      }catch(Exception ex) {

         System.out.println(ex);

      }

   }else{

      out.println("<html>");

      out.println("<head>");

      out.println("<title>Servlet upload</title>");  

      out.println("</head>");

      out.println("<body>");

      out.println("<p>No file uploaded</p>"); 

      out.println("</body>");

      out.println("</html>");

   }

%>


2.Client


2.1 Gradle

compile'com.squareup.retrofit2:retrofit:2.1.0'

compile'com.squareup.okhttp:okhttp:2.4.0'

compile'com.google.code.gson:gson:1.7.2'

compile'com.squareup.retrofit2:converter-gson:2.0.0-beta4'

compile'com.squareup.okhttp3:logging-interceptor:3.3.1'



2.2.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:id="@+id/btn_select"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="select file"
/>

<TextView
android:id="@+id/tv_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_select"
android:autoLink="web"/>

</RelativeLayout>


2.3. UploadService

POST의 주소는 적절히 넣어 주세요..경로 부분을 삭제하였습니다.

import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

public interface UploadService {

@Multipart
@POST("//imageUpload.jsp")
Call<ResponseBody> uploadFile(
@Part("description") RequestBody description,
@Part MultipartBody.Part file);

}



2.3. MyRetrofit2

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MyRetrofit2 {

public static final String URL = "http://192.168.0.95:8080/";

static Retrofit mRetrofit;

public static Retrofit getRetrofit2(){

if(mRetrofit == null){

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);

mRetrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
}
return mRetrofit;
}
}

2.4 Main.

import android.Manifest;
import android.app.Activity;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

private static final int PICK_FROM_FILE = 100;

Button btn_select;
TextView tv_message;

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

verifyStoragePermissions(this);

tv_message = (TextView)findViewById(R.id.tv_message);

btn_select = (Button)findViewById(R.id.btn_select);
btn_select.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

// Intent intent = new Intent(Intent.ACTION_PICK);
// intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
// intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// startActivityForResult(intent, PICK_FROM_FILE);

Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent chooser = Intent.createChooser(intent,"1a2a3a");

startActivityForResult(chooser, PICK_FROM_FILE);

}
});
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if(requestCode == PICK_FROM_FILE){
if(resultCode == RESULT_OK){
Uri selectImage = data.getData();
uploadImage(selectImage);
}
}
}

private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}



public void uploadImage(Uri uri){

UploadService service = MyRetrofit2.getRetrofit2().create(UploadService.class);

File file = new File(getRealPathFromURI(uri));
MultipartBody.Part body1 = prepareFilePart("image", uri);

RequestBody description = createPartFromString("hello, this is description speaking");

Call<ResponseBody> call = service.uploadFile(description, body1);
tv_message.setText(call.request().url().toString()); //todo 디버깅용

call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}



public static final String MULTIPART_FORM_DATA = "multipart/form-data";

@NonNull
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(
MediaType.parse(MULTIPART_FORM_DATA), descriptionString);
}

@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
File file = new File(getRealPathFromURI(fileUri));
RequestBody requestFile = RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}


// Storage Permissions variables
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};

//persmission method.
public static void verifyStoragePermissions(Activity activity) {
// Check if we have read or write permission
int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);

if (writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions( activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE );
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode == REQUEST_EXTERNAL_STORAGE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// save file

} else {
Toast.makeText(getApplicationContext(), "PERMISSION_DENIED", Toast.LENGTH_SHORT).show();
}
}
}

}


2.2 manifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


'android code' 카테고리의 다른 글

canvas에서 selector 적용하기  (0) 2016.08.10
안드로이드 파일 복사 퍼미션  (0) 2016.07.31
SparseArray for 문 돌리는 법  (0) 2016.07.27
벡터 드로어블 생성  (0) 2016.06.01
createCircularReveal 예제..  (0) 2016.05.31