SoFunction
Updated on 2025-03-01

Android implements multi-parameter file and data upload

This article shares the specific code for Android to implement multi-parameter files and data upload for your reference. The specific content is as follows

On code:

/**
  * Multiple pictures and parameters can be passed in
  *
  * @param actionUrl
  * Send address
  * @param params
  * Text parameters
  * @param files
  * File parameters
  * @return
  * @throws IOException
  */
 public static String mulpost(String actionUrl, Map<String, String> params,
 Map<String, File> files) throws IOException {
 String result = "";
 
 String BOUNDARY = ().toString();
 String PREFIX = "--", LINEND = "\r\n";
 String MULTIPART_FROM_DATA = "multipart/form-data";
 String CHARSET = "UTF-8";
 URL uri = new URL(actionUrl);
 HttpURLConnection conn = (HttpURLConnection) ();
 (5 * 1000);
 (true);// Allow input (true);// Allow output (false);
 ("POST"); // Post method ("connection", "keep-alive");
 ("Charsert", "UTF-8");
 ("Content-Type", MULTIPART_FROM_DATA
 + ";boundary=" + BOUNDARY);
 
 // First, group the parameters of the text type StringBuilder sb = new StringBuilder();
 for (<String, String> entry : ()) {
 (PREFIX);
 (BOUNDARY);
 (LINEND);
 ("Content-Disposition: form-data; name=\""
  + () + "\"" + LINEND);
 ("Content-Type: text/plain; charset=" + CHARSET + LINEND);
 ("Content-Transfer-Encoding: 8bit" + LINEND);
 (LINEND);
 (());
 (LINEND);
 }
 
 DataOutputStream outStream = new DataOutputStream(
 ());
 (().getBytes());
 
 // Send file data if (files != null)
 for (<String, File> file : ()) {
 StringBuilder sb1 = new StringBuilder();
 (PREFIX);
 (BOUNDARY);
 (LINEND);
 ("Content-Disposition: form-data; name=\"file\"; filename=\""
  + () + "\"" + LINEND);
 ("Content-Type: application/octet-stream; charset="
  + CHARSET + LINEND);
 (LINEND);
 (().getBytes());
 InputStream is = new FileInputStream(());
 byte[] buffer = new byte[1024];
 int len = 0;
 while ((len = (buffer)) != -1) {
  (buffer, 0, len);
 }
 
 ();
 (());
 }
 
 // Request end flag byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
 (end_data);
 ();
 
 InputStream is = ();
 InputStreamReader isr = new InputStreamReader(is, "utf-8");
 BufferedReader br = new BufferedReader(isr);
 result = ();
 ();
 ();
 return result;
 }

This is the method.

When using it, you can encapsulate it in your own class and call it directly. Remember to add network access and read system files permissions.

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

Since uploading is a time-consuming operation, it must be called in another thread.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.