android uploads files to the server code instance

  • 2020-05-19 05:49:32
  • OfStack

For uploading files, android is still very simple, and the upload in java is the same, basically familiar with the operation output stream and input stream! One thing that is particularly important is that you need some configuration of the content-type parameters! If all this is done, uploading is easy! The following is a tool class I wrote to upload:


package com.spring.sky.image.upload.network;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;
import android.util.Log;
/**
 * 
 *  Upload tool class 
 * @author spring sky
 * Email:vipa1888@163.com
 * QQ:840950105
 * MyName: Shi Mingzheng 
 */
public class UploadUtil {
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10*1000;   // timeout 
    private static final String CHARSET = "utf-8"; // Set the coding 
    /**
     * android Upload the file to the server 
     * @param file   Files that need to be uploaded 
     * @param RequestURL   The request of rul
     * @return   Returns the content of the response 
     */
    public static String uploadFile(File file,String RequestURL)
    {
        String result = null;
        String  BOUNDARY =  UUID.randomUUID().toString();  // The boundary identification     Randomly generated 
        String PREFIX = "--" , LINE_END = "\r\n"; 
        String CONTENT_TYPE = "multipart/form-data";   // Content type 

        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true);  // Allow input stream 
            conn.setDoOutput(true); // Allowed output stream 
            conn.setUseCaches(false);  // Caching is not allowed 
            conn.setRequestMethod("POST");  // Request way 
            conn.setRequestProperty("Charset", CHARSET);  // Set the coding 
            conn.setRequestProperty("connection", "keep-alive");   
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); 

            if(file!=null)
            {
                /**
                 *  When the file is not empty, wrap the file and upload it 
                 */
                DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 *  Here are the highlights: 
                 * name The values inside are required by the server side key    Only this key  To get the corresponding file 
                 * filename Is the name of the file, including the suffix     Such as :abc.png  
                 */

                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); 
                sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while((len=is.read(bytes))!=-1)
                {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 *  Get response code   200= successful 
                 *  When the response is successful, get the flow of the response   
                 */
                int res = conn.getResponseCode();  
                Log.e(TAG, "response code:"+res);
//                if(res==200)
//                {
                    Log.e(TAG, "request success");
                    InputStream input =  conn.getInputStream();
                    StringBuffer sb1= new StringBuffer();
                    int ss ;
                    while((ss=input.read())!=-1)
                    {
                        sb1.append((char)ss);
                    }
                    result = sb1.toString();
                    Log.e(TAG, "result : "+ result);
//                }
//                else{
//                    Log.e(TAG, "request error");
//                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

The parameters are 1 File file and 1 URL request for uploading. However, it is important to note that since the network request is needed, please do not forget to add 1 access to wang luodan to the android client when uploading.


Another point is that we need to pay attention to 1: I am a server side javaEE, I found that in the upload process, if the file identification name is java keyword, there will be a lot of location problems in the upload process! So you may not use keywords!

Here's the code for Activity:


package com.spring.sky.image.upload;

import java.io.File;
import com.spring.sky.image.upload.network.UploadUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
/**
 * Activity  Upload interface 
 * @author spring sky
 * Email:vipa1888@163.com
 * QQ:840950105
 * MyName: Shi Mingzheng 
 *
 */
public class MainActivity extends Activity implements OnClickListener{
    private static final String TAG = "uploadImage";
    private static String requestURL = "http://192.168.1.14:8080/SetBlobData/img!up";
    private Button selectImage,uploadImage;
    private ImageView imageView;

    private String picPath = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        selectImage = (Button) this.findViewById(R.id.selectImage);
        uploadImage = (Button) this.findViewById(R.id.uploadImage);
        selectImage.setOnClickListener(this);
        uploadImage.setOnClickListener(this);

        imageView = (ImageView) this.findViewById(R.id.imageView);

        
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.selectImage:
            /***
             *  This is the call android The built-in intent To filter image files     And you can filter the others as well   
             */
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, 1);
            break;
        case R.id.uploadImage:
            File file = new File(picPath);
            if(file!=null)
            {
                String request = UploadUtil.uploadFile( file, requestURL);
                uploadImage.setText(request);
            }
            break;
        default:
            break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==Activity.RESULT_OK)
        {
            /**
             *  When the selected image is not empty, get the image in the path   
             */
            Uri uri = data.getData();
            Log.e(TAG, "uri = "+ uri);
            try {
                String[] pojo = {MediaStore.Images.Media.DATA};

                Cursor cursor = managedQuery(uri, pojo, null, null,null);
                if(cursor!=null)
                {
                    ContentResolver cr = this.getContentResolver();
                    int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    String path = cursor.getString(colunm_index);
                    /***
                     *  I'm going to add that 1 The judgment is for the sake of the first 3 Side software selection, such as: use the first 3 The file manager on the side you choose is not the file 1 It must be a picture. In this case, we can judge the suffix name of the file 
                     *  If it is a picture format, then it is ok    
                     */
                    if(path.endsWith("jpg")||path.endsWith("png"))
                    {
                        picPath = path;
                        Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                        imageView.setImageBitmap(bitmap);
                    }else{alert();}
                }else{alert();}

            } catch (Exception e) {
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void alert()
    {
        Dialog dialog = new AlertDialog.Builder(this)
        .setTitle(" prompt ")
        .setMessage(" You did not select a valid image ")
        .setPositiveButton(" determine ",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        picPath = null;
                    }
                })
        .create();
        dialog.show();
    }

}

layout code:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text=" Choose picture "
    android:id="@+id/selectImage"
    />
    <Button  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text=" To upload pictures "
    android:id="@+id/uploadImage"
    />
     <ImageView  
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/imageView"
    />
</LinearLayout>

If you want to upload other files, you can modify the filter condition. At the same time, the type 1 of the file must be the same as the type 1 on the server side. Otherwise, the upload will fail!


Related articles: