OkHttpUtils.post() uploads files (Android front-end upload and server background reception)

Android terminal

1. First of all, you need to use the package, now add dependencies in build.gradle(app)

implementation 'com.github.xxl6097:okhttputils:2.4.1'
//Or implementation 'com.zhy:okhttputils:2.6.2'
//The first one used here

Without further ado, let’s get straight to the code.

2. Upload code multiFileUpload method

public void multiFileUpload(ArrayList<Image> image) throws UnsupportedEncodingException {<!-- -->
Be a json string and set the encoding.content(new Gson().toJson(new User("zhy", "123"))) //Use Gson to convert the User object into a Json string as content .build() .execute(new MyStringCallback()); }
        mDialog = new SpotsDialog(SendFleaActivity.this,"Uploading...");
        final String url = AppConstant.uploadflea;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Disposition", "form-data;filename=enctype");

        PostFormBuilder build = OkHttpUtils.post();
        for (int i=0;i<image.size();i + + ){<!-- -->
            //Determine the file is legal
            if(!new File(image.get(i).getPath()).exists()){<!-- -->
                Toast.makeText(SendFleaActivity.this,"The file does not exist, please modify the path",Toast.LENGTH_LONG).show();
                return;
            }
            //Compress the image and get the file format

            File file = new File(BitmapUtil.compressImage(image.get(i).getPath()));
            //Generate a random file name, add file, name is the user id
            build.addFile(getuserid(getApplicationContext()),
                    getopenid(this) +
                            Universal.generateRandomFilename() + "01.png", file);
        }
        build.addHeader("head", URLEncoder.encode(getBean(), "UTF-8"))
                .url(url)
                .build()
                .execute(new StringCallback() {<!-- -->
                    @Override
                    public void onError(Call call, Exception e) {<!-- -->
                        mDialog.dismiss();
                        Toast.makeText(SendFleaActivity.this, "Server connection failed",Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(Call call, String s) {<!-- -->

                        mDialog.dismiss();
                        try {<!-- -->
                            Toast.makeText(SendFleaActivity.this, URLDecoder.decode(s, "UTF-8"),Toast.LENGTH_LONG).show();
                        } catch (UnsupportedEncodingException e) {<!-- -->
                            e.printStackTrace();
                        }
// if (s.equals("0")){<!-- -->
// Toast.makeText(SendFleaActivity.this, s + "Published successfully",Toast.LENGTH_LONG).show();
// }else {<!-- -->
// Toast.makeText(SendFleaActivity.this,s + "Publish failed",Toast.LENGTH_LONG).show();
//
// }
                    }
                    @Override
                    public void onBefore(Request request) {<!-- -->
                        super.onBefore(request);

                        mDialog.show();
                    }
                });
    }

3. There are few code comments, and other methods are used in it. For example, random functions are used to name random file names. Let’s put the generateRandomFilename() method

public static String generateRandomFilename(){<!-- -->
    String RandomFilename = "";
    Random rand = new Random();//Generate random numbers
    int random = rand.nextInt();

    Calendar calCurrent = Calendar.getInstance();
    int intDay = calCurrent.get(Calendar.DATE);
    int intMonth = calCurrent.get(Calendar.MONTH) + 1;
    int intYear = calCurrent.get(Calendar.YEAR);
    String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" +
            String.valueOf(intDay) + "_";

    RandomFilename = "_" + now + String.valueOf(random > 0 ? random : ( -1) * random);

    return RandomFilename;
}

4. The Image class

public class Image implements Parcelable {<!-- -->

    private int id;
    private String path;
    private String thumbPath;
    private boolean isSelect;
    private String folderName;
    private String name;
    private long date;

    public int getId() {<!-- -->
        return id;
    }

    public void setId(int id) {<!-- -->
        this.id = id;
    }

    public String getPath() {<!-- -->
        return path;
    }

    public void setPath(String path) {<!-- -->
        this.path = path;
    }

    public String getThumbPath() {<!-- -->
        return thumbPath;
    }

    public void setThumbPath(String thumbPath) {<!-- -->
        this.thumbPath = thumbPath;
    }

    public boolean isSelect() {<!-- -->
        return isSelect;
    }

    public void setSelect(boolean select) {<!-- -->
        isSelect = select;
    }

    public String getFolderName() {<!-- -->
        return folderName;
    }

    public void setFolderName(String folderName) {<!-- -->
        this.folderName = folderName;
    }

    public String getName() {<!-- -->
        return name;
    }

    public void setName(String name) {<!-- -->
        this.name = name;
    }

    public long getDate() {<!-- -->
        return date;
    }

    public void setDate(long date) {<!-- -->
        this.date = date;
    }

    @Override
    public boolean equals(Object o) {<!-- -->
        if (o instanceof Image) {<!-- -->
            return this.path.equals(((Image) o).getPath());
        }
        return false;
    }

    @Override
    public int describeContents() {<!-- -->
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {<!-- -->
        dest.writeInt(this.id);
        dest.writeString(this.path);
        dest.writeString(this.thumbPath);
        dest.writeByte(this.isSelect ? (byte) 1 : (byte) 0);
        dest.writeString(this.folderName);
        dest.writeString(this.name);
        dest.writeLong(this.date);
    }

    public Image() {<!-- -->
    }

    protected Image(Parcel in) {<!-- -->
        this.id = in.readInt();
        this.path = in.readString();
        this.thumbPath = in.readString();
        this.isSelect = in.readByte() != 0;
        this.folderName = in.readString();
        this.name = in.readString();
        this.date = in.readLong();
    }

    public static final Creator<Image> CREATOR = new Creator<Image>() {<!-- -->
        @Override
        public Image createFromParcel(Parcel source) {<!-- -->
            return new Image(source);
        }

        @Override
        public Image[] newArray(int size) {<!-- -->
            return new Image[size];
        }
    };
}

5. Compressed image method class BitmapUtil

public class BitmapUtil {<!-- -->
    public static Bitmap calculateInSampleSize(String imagePath) {<!-- -->
        // Setting parameters
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // Only get the size information of the image instead of loading the entire image into memory to avoid memory overflow
        // Output image data
        //orginBitmap=: size: 14745600 width: 1440 height:2560
// Bitmap originBitmap = BitmapFactory.decodeFile(imagePath, options);
// Log.w("originBitmap=", "size: " + originBitmap.getByteCount() +
// " width: " + originBitmap.getWidth() + " height:" + originBitmap.getHeight());
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = 2; //Default pixel compression ratio, compressed to 1/2 of the original image
        int minLen = Math.min(height, width); // Minimum side length of the original image
        if (minLen > 100) {<!-- --> // If the minimum side length of the original image is greater than 100dp (I think the unit here is dp, not px)
            float ratio = (float) minLen / 100.0f; // Calculate pixel compression ratio
            inSampleSize = (int) ratio;
        }
        options.inSampleSize = inSampleSize; // Set to the compression ratio just calculated
        options.inJustDecodeBounds = false; // After calculating the compression ratio, you can load the original image this time
        Bitmap bm = BitmapFactory.decodeFile(imagePath, options); // Decode file
        //size: 74256 width: 102 height:182
        Log.w("bm=", "size: " + bm.getByteCount() + " width: " + bm.getWidth() + " heigth:" + bm.getHeight()) ; // Output image data
        return bm;
    }


    /**
     * @param reqWidth required width
     * @param reqHeight required high
     */
    public static Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight) {<!-- -->
        //Options only saves the image size, does not save the image to memory
        BitmapFactory.Options options = new BitmapFactory.Options();
        //Set this property to true, do not load the image into memory, and only return the width and height of the image to options.
        // The first analysis sets inJustDecodeBounds to true to obtain the image size.
        options.inJustDecodeBounds = true;
        //Load the image first
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        //Reset this property to false, load the image and return
        // Use the obtained inSampleSize value to parse the image again
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {<!-- -->
        int width = options.outWidth;
        int height = options.outHeight;
        int inSampleSize = 1;
        int widthRatio = Math.round((float) width / (float) reqWidth);
        int heightRatio = Math.round((float) height / (float) reqHeight);
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        return inSampleSize;
    }

    private static String PHOTO_FILE_NAME = "PMSManagerPhoto";

    /**
     * Get the rotation angle of the image
     *
     * @param filePath
     * @return
     */
    public static int getRotateAngle(String filePath) {<!-- -->
        int rotate_angle = 0;
        try {<!-- -->
            ExifInterface exifInterface = new ExifInterface(filePath);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {<!-- -->
                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotate_angle = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotate_angle = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotate_angle = 270;
                    break;
            }
        } catch (IOException e) {<!-- -->
            e.printStackTrace();
        }
        return rotate_angle;
    }

    /**
     * Rotate picture angle
     *
     * @param angle
     * @param bitmap
     * @return
     */
    public static Bitmap setRotateAngle(int angle, Bitmap bitmap) {<!-- -->

        if (bitmap != null) {<!-- -->
            Matrix m = new Matrix();
            m.postRotate(angle);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;

    }

    //Convert to a circular bitmap
    public static Bitmap createCircleImage(Bitmap source) {<!-- -->
        int length = source.getWidth() < source.getHeight() ? source.getWidth() : source.getHeight();
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        Bitmap target = Bitmap.createBitmap(length, length, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(target);
        canvas.drawCircle(length / 2, length / 2, length / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(source, 0, 0, paint);
        return target;
    }



    /**
     * Image compression - quality compression
     *
     * @param filePath source image path
     * @return compressed path
     */

    public static String compressImage(String filePath) {<!-- -->

        //Original file
        File oldFile = new File(filePath);


        //Compressed file path photo path/
        String targetPath = oldFile.getPath();
        int quality = 50; //Compression ratio 0-100
        Bitmap bm = getSmallBitmap(filePath);//Get a picture of a certain size
        int degree = getRotateAngle(filePath);//Get the photo angle

        if (degree != 0) {<!-- -->//Rotate the photo angle to prevent the avatar from being displayed horizontally
            bm = setRotateAngle(degree,bm);
        }
        File outputFile = new File(targetPath);
        try {<!-- -->
            if (!outputFile.exists()) {<!-- -->
                outputFile.getParentFile().mkdirs();
                //outputFile.createNewFile();
            } else {<!-- -->
                outputFile.delete();
            }
            FileOutputStream out = new FileOutputStream(outputFile);
            bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
            out.close();
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
            return filePath;
        }
        return outputFile.getPath();
    }

    /**
     * Obtain image information according to the path and compress it proportionally, returning bitmap
     */
    public static Bitmap getSmallBitmap(String filePath) {<!-- -->
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; //Only parse the edges of the image and obtain the width and height
        BitmapFactory.decodeFile(filePath, options);
        // Calculate zoom ratio
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // Completely parse the image and return bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }
}

6. In the multiFileUpload of file upload, the following sentence is to post a header file. Here I put the text information I need to upload here. It can also be placed in param, but I found that it cannot be read this way. Very annoying, I can’t find the reason, so I’ll put it in the header file for the time being. The getBean() method is my text information. I can modify it here and delete it if I don’t need it.

build.addHeader("head", URLEncoder.encode(getBean(), "UTF-8"))

Then there seems to be nothing else. If you find any missing codes, please contact us in time.
So here is all the Android stuff

Server code

Anyway, without further ado, let’s go straight to the code//Um, why don’t you allow copying? The copying crashes. I don’t know if it’s a problem with CSDN or me.

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet(description = "flea product release",urlPatterns = {<!-- -->"/UploadServlet"})

public class UploadServlet extends HttpServlet {<!-- -->
    private static final long serialVersionUID = 1L;

    //Upload file storage directory
    private static final String UPLOAD_DIRECTORY = "upload";

    //Upload configuration
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
    private static String SUCCESS = null; // 50MB
    private static String FAIL = null;
    static {<!-- -->
        try {<!-- -->
            SUCCESS = URLEncoder.encode("Published successfully", "UTF-8");
            FAIL = URLEncoder.encode("Publish failed", "UTF-8");
        } catch (UnsupportedEncodingException e) {<!-- -->
            e.printStackTrace();
        }
    }


    /**
     * Upload data and save files
     */
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {<!-- -->
        request.setCharacterEncoding("utf-8");

        // Check whether it is a multimedia upload
        if (!ServletFileUpload.isMultipartContent(request)) {<!-- -->
            // Stop if not
            PrintWriter writer = response.getWriter();
            writer.println("Error: The form must contain enctype=multipart/form-data");
            writer.flush();
            return;
        }
// System.out.println("111" + getparam(request));
// This sentence is to get the header file
        String goods =
                URLDecoder.decode(getHeadersInfo(request).getOrDefault("head","Failed"), "UTF-8");
// System.out.println(goods);
        saveImage(request,response, DBUtil.Insert_goods(goods));

// response.getWriter().println(back);

        // Jump to message.jsp
// request.getServletContext().getRequestDispatcher("/message.jsp").forward(
// request, response);



    }
    public static void saveImage(HttpServletRequest request,HttpServletResponse response,int goodid) throws IOException {<!-- -->
        //Configure upload parameters
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Set the memory threshold - when exceeded, a temporary file will be generated and stored in the temporary directory
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        //Set the temporary storage directory
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        //Set the maximum file upload value
        upload.setFileSizeMax(MAX_FILE_SIZE);

        //Set the maximum request value (including file and form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        //Chinese processing
        upload.setHeaderEncoding("UTF-8");
// Request.QueryString["name"];

        // Construct a temporary path to store uploaded files
        // This path is relative to the directory of the current application
        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;


        //Create the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {<!-- -->
            uploadDir.mkdir();
        }

        try {<!-- -->
            Enumeration<String> enumeration = request.getParameterNames();
            while(enumeration.hasMoreElements()){<!-- -->
                String name = enumeration.nextElement();
                String value = new String(request.getParameter(name).getBytes("iso8859-1"),"utf-8");
                System.out.println(name + " : " + value);}

            // Parse the requested content to extract file data
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null & amp; & amp; formItems.size() > 0) {<!-- -->
                int i = 0;
                //Iterate over form data
                for (FileItem item : formItems) {<!-- -->



// System.out.println(item.getFieldName());
                    // Handle fields that are not in the form
                    if (!item.isFormField()) {<!-- -->
                        String fileName = new File(item.getName()).getName();
// System.out.println(item.getName() + " + + + + + + + + + + + + ");
                        //Save image information to database
                        if (goodid!=0) {<!-- -->
                            if (i==0){<!-- -->
                                DBUtil.Insert_one(DBUtil.TAB_flea_goods,goodid,"url",DBUtil.THIS_URL + item.getName());
                                i=2;
                            }
                            DBUtil.inser_image(DBUtil.TAB_flea_pic_url, goodid, item.getName());


                            String filePath = uploadPath + File.separator + fileName;
                            File storeFile = new File(filePath);
                            // Output the upload path of the file in the console
                            System.out.println(filePath);
                            //Save the file to the hard disk
                            item.write(storeFile);

// request.setAttribute("message",
// "File uploaded successfully!");
                        }
// else {<!-- -->
// response.getWriter().println(FAIL);
                            request.setAttribute("message",
                                    "Error message: " + "Publishing failed");
// }
                    }
                }response.getWriter().println(SUCCESS);
            }
        } catch (Exception ex) {<!-- -->
            try {<!-- -->
                response.getWriter().println(FAIL);
            }catch (Exception e){<!-- -->
                response.getWriter().close();
            }
            ex.printStackTrace();
// request.setAttribute("message",
// "Error message: " + ex.getMessage());
        }
    }

      *

     * @param request

     * @return

     */

    public static Map<String, String> getHeadersInfo(HttpServletRequest request) {<!-- -->
        Map<String, String> map = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {<!-- -->
            String key = (String) headerNames.nextElement();

            String value = request.getHeader(key);
// System.out.println(key + ":" + value);
            map.put(key, value);
        }
        return map;
    }
}

In fact, you only need to look at the saveImage method here. This is what saves the image. The rest is the process I stored in the database. Just delete it. You can refer to it if you need it. emm is like this at the moment. If you have any questions, please contact me in time. I will help. Nothing,,,,