7.3.1 Android File Upload
Category Android Basic Tutorial
Introduction to This Section
>
This section, like the next one on file downloading, comes with a caution... Nowadays, in actual development, when it comes to file uploading, one would not typically write their own upload code. Instead, they would generally integrate a third-party network library for image uploads, such as android-async-http, okhttp, etc. In addition, Qiniu also provides APIs for both downloading and uploading, and those who are interested can visit the official website to check the relevant API documentation! For this section, if you are interested, just take a look!
1. Key Methods for Image Upload Used in the Project:
After much thought, I decided to first post the core method for image uploading used in the company's project. Here, a third-party library is used: android-async-http.jar, you can download this library from GitHub yourself~ Then just call the following method, and change the URL as needed!
The core method for uploading images is as follows:
private void sendImage(Bitmap bm)
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 60, stream);
byte[] bytes = stream.toByteArray();
String img = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.add("img", img);
client.post("http:xxx/postIcon", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
Toast.makeText(MainActivity.this, "Upload Success!", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
Toast.makeText(MainActivity.this, "Upload Fail!", Toast.LENGTH_LONG).show();
}
});
}
2. Uploading Files Using HttpConnection:
```
public class SocketHttpRequester
{
/**
* Send XML data
* @param path Request URL
* @param xml XML data
* @param encoding Encoding
* @return
* @throws Exception
*/
public static byte[] postXml(String path, String xml, String encoding) throws Exception{
byte[] data = xml.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml; charset="+ encoding);
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
if(conn.getResponseCode()==200){
return readStream(conn.getInputStream());
}
return null;
}
/**
* Directly submit data to the server via HTTP protocol, implementing the following form submission function:
* <FORM METHOD=POST ACTION="http://192.168.0.200:8080/ssi/fileload/test.do" enctype="multipart/form-data">
<INPUT TYPE="text" NAME="name">
<INPUT TYPE="text" NAME="id">
<input type="file" name="imagefile"/>
<input type="file" name="zip"/>
</FORM>
* @param path Upload path (Note: Avoid using paths like localhost or 127.0.0.1 for testing,
* because they will point to the mobile emulator, you can use paths like http://www.baidu.com or http://192.168.1.10:8080 for testing)
* @param params Request parameters key as parameter name, value as parameter value
* @param files Files to be uploaded
*/
public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception
{
//Data separator
final String BOUNDARY = "---------------------------7da2137580612";
//Data end flag "---------------------------7da2137580612--"
final String endline = "--" + BOUNDARY + "--/r/n";
//The following two for loops are all to get the total length of the data parameter, depending on the type of form
//First get the total length of the file type data (including the file separator)
int fileDataLength = 0;
Socket socket = new Socket(InetAddress.getByName(url.getHost()), port); // Get an output stream (from Android to web) OutputStream outStream = socket.getOutputStream(); // Next, complete the sending of the HTTP request header String requestmethod = "POST " + url.getPath() + " HTTP/1.1\r\n"; outStream.write(requestmethod.getBytes()); // Build accept String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, /\r\n"; outStream.write(accept.getBytes()); // Build language String language = "Accept-Language: zh-CN\r\n"; outStream.write(language.getBytes()); // Build content type String contenttype = "Content-Type: multipart/form-data; boundary=" + BOUNDARY + "\r\n"; outStream.write(contenttype.getBytes()); // Build content length String contentlength = "Content-Length: " + dataLength + "\r\n"; outStream.write(contentlength.getBytes()); // Build alive String alive = "Connection: Keep-Alive\r\n"; outStream.write(alive.getBytes()); // Build host String host = "Host: " + url.getHost() + ":" + port + "\r\n"; outStream.write(host.getBytes()); // After writing the HTTP request header, write a carriage return and line feed according to the HTTP protocol outStream.write("\r\n".getBytes()); // Send out all the entity data of the text type outStream.write(textEntity.toString().getBytes());
// Send out all the entity data of the file type for (FormFile uploadFile : files) { StringBuilder fileEntity = new StringBuilder(); fileEntity.append("--"); fileEntity.append(BOUNDARY); fileEntity.append("\r\n"); fileEntity.append("Content-Disposition: form-data;name=\"" + uploadFile.getParameterName() + "\";filename=\"" + uploadFile.getFilename() + "\"\r\n"); fileEntity.append("Content-Type: " + uploadFile.getContentType() + "\r\n\r\n"); outStream.write(fileEntity.toString().getBytes()); // Read and write at the same time if (uploadFile.getInStream() != null) { byte[] buffer = new byte[1024]; int len = 0; while ((len = uploadFile.getInStream().read(buffer, 0, 1024)) != -1) { outStream.write(buffer, 0, len); } uploadFile.getInStream().close(); } else { outStream.write(uploadFile.getData(), 0, uploadFile.getData().length); } outStream.write("\r\n".getBytes()); } // Send the end of the data mark below, indicating that the data has ended outStream.write(endline.getBytes()); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // Read the data returned by the web server, and determine whether the request code is 200. If it is not 200, it means the request has failed if (reader.readLine().indexOf("200") == -1) { return false; } outStream.flush(); outStream.close(); reader.close(); socket.close(); return true;
/**
- Submit data to the server
- @param path Upload path (Note: Avoid using paths like localhost or 127.0.0.1 for testing, as they will point to the mobile emulator. You can use paths like http://www.baidu.com or http://192.168.1.10:8080 for testing)
- @param params Request parameters key as parameter name, value as parameter value
- @param file Upload file / public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception { return post(path, params, new FormFile[]{file}); } /*
- Submit data to the server
- @param path Upload path (Note: Avoid using paths like localhost or 127.0.0.1 for testing, as they will point to the mobile emulator. You can use paths like http://www.baidu.com or http://192.168.1.10:8080 for testing)
- @param params Request parameters key as parameter name, value as parameter value
- @param encode Encoding
/
public static byte[] postFromHttpClient(String path, Map<String, String> params, String encode) throws Exception {
// Used to store request parameters
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, encode);
HttpPost httppost = new HttpPost(path);
httppost
//String params = "method=save&name="+ URLEncoder.encode("Lao Bi", "UTF-8")+ "&age=28&"; //Parameters to be sent
StringBuilder parambuilder = new StringBuilder("");
if(params!=null && !params.isEmpty())
{
for(Map.Entry<String, String> entry : params.entrySet())
{
parambuilder.append(entry.getKey()).append("=")
.append(URLEncoder.encode(entry.getValue(), encode)).append("&");
}
parambuilder.deleteCharAt(parambuilder.length()-1);
}
byte[] data = parambuilder.toString().getBytes();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//Set to allow sending request parameters
conn.setDoOutput(true);
//Set to not cache
conn.setUseCaches(false);
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("POST");
//The following sets the HTTP request header
conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */");
conn.setRequestProperty("Accept-Language", "zh-CN");
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setRequestProperty("Connection", "Keep-Alive");
//Send parameters
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(data); //Send the parameters
outStream.flush();
outStream.close();
if(conn.getResponseCode()==200)
{
return readStream(conn.getInputStream());
}
return null;
}
/**
- Read the stream
- @param inStream
- @return Byte array
- @throws Exception
*/
public static byte[] readStream(InputStream inStream) throws Exception
{
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len=inStream.read(buffer)) != -1)
{
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
}
I stumbled upon a reprinted article from before, you can check it out with the above...: Using HttpConnection to upload mp3 files
Summary of this section:
>
Let's just ignore this section... For advanced topics like file uploads, I'll just teach you to use third-party tools. If you need to use third-party tools in the project, just copy the code from 1, and import android-async-http!
-1.0 Android Basic Tutorial for Beginners
-1.0.1 Latest Android Basic Tutorial Table of Contents for 2015
-1.1 Background and System Architecture Analysis
-1.2 Development Environment Setup
-1.2.1 Developing Android APPs with Eclipse + ADT + SDK
-1.2.2 Developing Android APPs with Android Studio
-1.3 Solving SDK Update Issues
-1.4 Genymotion Emulator Installation
-1.5.1 Git Tutorial on Basic Operations of Local Repositories
-1.5.2 Git: Setting Up a Remote Repository with GitHub
-1.6 How to Play with 9 (Jiu Mei) Images
-[1.7 Interface Prototype Design](android-
2.5.4 Basic Usage of AutoCompleteTextView (Auto-Complete Text Box)
2.5.8 Detailed Explanation of Notification (Status Bar Notification)
2.6.4 Simple Usage of DrawerLayout (Official Side-Slide Menu)
3.6 Responding to System Setting Events (Configuration Class)
4.4.2 Further Exploration of ContentProvider - Document Provider
5.2.1 Detailed Explanation of Fragment - Implementation of Bottom Navigation Bar (Method 1)
5.2.2 Detailed Explanation of Fragment - Implementation of Bottom Navigation Bar (Method 2)
[5.2.3 Detailed Explanation of Fragment - Implementation
8.3.4 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 1)
8.3.5 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 2)
8.3.6 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 3)
8.3.7 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 4)
8.3.8 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 5)
8.3.14 Paint Enum/Constant Values and ShadowLayer Shadow Effect
8.3.17 Detailed Explanation of Canvas API (Part 2) - Clipping Method Collection
8.3.18 Detailed Explanation of Canvas API (Part 3) - Matrix and drawBitmapMesh
8.4.3 Android Animation Collection - Property Animation - First Encounter
8.4.4 Android Animation Collection - Property Animation - Revisited
11.0 "2015 Latest Android Basic Tutorial" Completion Celebration~
[12.1 Android Practice: DrySister Girl Viewing App (First Edition) - Project Setup and Simple Implementation](android-tutorial-