Android Volley implements the file upload function, androidvolley
Volley does not explain it. An official android Network request library.
The Source Code address is:
Git@github.com: com314159/VolleyMultiPartRequest. git
Is based on
Https://github.com/smanikandan14/Volley-demo
The great god modified it, but the code of the great God had a bug, and the file upload was not successful.
Note: okhttp is also integrated in my demo. Skip this class if you don't need it.
Implementation Method:
1. Add three jar packages,
Httpcore-4.3.2.jar
Httpclient-4.3.5.jar
Httpmime-4.3.5.jar
2. Implement MultiPartStack
Package com. example. volleytest; import java. io. file; import java. io. IOException; import java. util. map; import org. apache. http. httpEntity; import org. apache. http. httpResponse; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpDelete; import org. apache. http. client. methods. httpEntityEnclosingRequestBase; import org. apache. http. client. methods. httpGet; import org. apache. http. clie Nt. methods. httpPatch; import org. apache. http. client. methods. httpPost; import org. apache. http. client. methods. httpPut; import org. apache. http. client. methods. httpUriRequest; import org. apache. http. entity. byteArrayEntity; import org. apache. http. entity. contentType; import org. apache. http. entity. mime. httpMultipartMode; import org. apache. http. entity. mime. multipartEntityBuilder; import org. apache. http. entity. mime. Content. fileBody; import org. apache. http. entity. mime. content. stringBody; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. params. httpConnectionParams; import org. apache. http. params. httpParams; import org. apache. http. protocol. HTTP; import com. android. volley. authFailureError; import com. android. volley. request; import com. android. volley. request. method; import com. android. volley. to Olbox. hurlStack;/*** @ author ZhiCheng Guo * @ version 11:00:52 AM, January 1, October 7, 2014 this Stack is used to upload files. If this Stack is not available, the file is not uploaded successfully */public class MultiPartStack extends HurlStack {@ SuppressWarnings ("unused") private static final String TAG = MultiPartStack. class. getSimpleName (); private final static String HEADER_CONTENT_TYPE = "Content-Type"; @ Overridepublic HttpResponse response mrequest (Request <?> Request, Map <String, String> additionalHeaders) throws IOException, AuthFailureError {if (! (Request instanceof MultiPartRequest) {return super. extends mrequest (request, additionalHeaders);} else {return callback mmultipartrequest (request, additionalHeaders);} private static void addHeaders (HttpUriRequest httpRequest, Map <String, String> headers) {for (String key: headers. keySet () {httpRequest. setHeader (key, headers. get (key) ;}} public HttpResponse implements mmultipartrequest (Request <?> Request, Map <String, String> additionalHeaders) throws IOException, AuthFailureError {HttpUriRequest httpRequest = requests (requests, requests); addHeaders (httpRequest, additionalHeaders); addHeaders (httpRequest, request. getHeaders (); HttpParams httpParams = httpRequest. getParams (); int timeoutMs = request. getTimeoutMs (); // TODO: Reevaluate this connection timeout based on More wide-scale // data collection and possibly different for wifi. 3G. httpConnectionParams. setConnectionTimeout (httpParams, 5000); HttpConnectionParams. setSoTimeout (httpParams, timeoutMs);/* Make a thread safe connection manager for the client */HttpClient httpClient = new DefaultHttpClient (httpParams); return httpClient.exe cute (httpRequest );} static HttpUriRequest createMultiPartRequest (Re Quest <?> Request, Map <String, String> additionalHeaders) throws AuthFailureError {switch (request. getMethod () {case Method. DEPRECATED_GET_OR_POST: {// This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. otherwise, it is assumed that the request is a POST. byte [] postBody = request. getB Ody (); if (postBody! = Null) {HttpPost postRequest = new HttpPost (request. getUrl (); if (request. getBodyContentType ()! = Null) postRequest. addHeader (HEADER_CONTENT_TYPE, request. getBodyContentType (); HttpEntity entity; entity = new ByteArrayEntity (postBody); postRequest. setEntity (entity); return postRequest;} else {return new HttpGet (request. getUrl () ;}} case Method. GET: return new HttpGet (request. getUrl (); case Method. DELETE: return new HttpDelete (request. getUrl (); case Method. POST: {HttpPost postRequest = New HttpPost (request. getUrl (); postRequest. addHeader (HEADER_CONTENT_TYPE, request. getBodyContentType (); setMultiPartBody (postRequest, request); return postRequest;} case Method. PUT: {HttpPut putRequest = new HttpPut (request. getUrl (); if (request. getBodyContentType ()! = Null) putRequest. addHeader (HEADER_CONTENT_TYPE, request. getBodyContentType (); setMultiPartBody (putRequest, request); return putRequest;} // Added in source code of Volley libray. case Method. PATCH: {HttpPatch patchRequest = new HttpPatch (request. getUrl (); if (request. getBodyContentType ()! = Null) patchRequest. addHeader (HEADER_CONTENT_TYPE, request. getBodyContentType (); return patchRequest;} default: throw new IllegalStateException ("Unknown request method. ") ;}}/*** If Request is MultiPartRequest type, then set MultipartEntity in the * httpRequest object. ** @ param httpRequest * @ param request * @ throws AuthFailureError */private static void setMultiPartBody (HttpEntityEnclosingR EquestBase httpRequest, Request <?> Request) throws AuthFailureError {// Return if Request is not MultiPartRequestif (! (Request instanceof MultiPartRequest) {return;} // MultipartEntity multipartEntity = new // MultipartEntity (HttpMultipartMode. BROWSER_COMPATIBLE); MultipartEntityBuilder builder = MultipartEntityBuilder. create ();/* example for setting a HttpMultipartMode */builder. setMode (HttpMultipartMode. BROWSER_COMPATIBLE); // Iterate the fileUploadsMap <String, File> fileUpload = (MultiPartRequest) request ). getFileUploads (); for (Map. entry <String, File> entry: fileUpload. entrySet () {builder. addPart (String) entry. getKey (), new FileBody (File) entry. getValue ();} ContentType contentType = ContentType. create (HTTP. PLAIN_TEXT_TYPE, HTTP. UTF_8); // Iterate the stringUploadsMap <String, String> stringUpload = (MultiPartRequest) request ). getStringUploads (); for (Map. entry <String, String> entry: stringUpload. entrySet () {try {builder. addPart (String) entry. getKey (), new StringBody (String) entry. getValue (), contentType);} catch (Exception e) {e. printStackTrace () ;}} httpRequest. setEntity (builder. build ());}}
3. Implement MultiPartRequest to facilitate expansion
Package com. example. volleytest; import java. io. file; import java. util. map;/*** @ author ZhiCheng Guo * @ version October 7, 2014 11:04:36 */public interface MultiPartRequest {public void addFileUpload (String param, File file); public void addStringUpload (String param, string content); public Map <String, File> getFileUploads (); public Map <String, String> getStringUploads ();}
/*** Copyright 2013 Mani Selvaraj *** Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file License t in compliance with the License. * You may be obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "as is" BASIS ,* Without warranties or conditions of any kind, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com. example. volleytest; import java. io. file; import java. io. unsupportedEncodingException; import java. util. hashMap; import java. util. map; import com. android. volley. networkResponse; import com. android. volley. request; impor T com. android. volley. response; import com. android. volley. response. errorListener; import com. android. volley. response. listener; import com. android. volley. toolbox. httpHeaderParser;/*** MultipartRequest-To handle the large file uploads. * Extended from JSONRequest. you might want to change to StringRequest based on your response type. * @ author Mani Selvaraj **/public class MultiPartStringRequest ext Ends Request <String> implements MultiPartRequest {private final Listener <String> mListener;/* To hold the parameter name and the File to upload */private Map <String, file> fileUploads = new HashMap <String, File> ();/* To hold the parameter name and the string content to upload */private Map <String, string> stringUploads = new HashMap <String, String> ();/*** Creates a new request with the given method. ** @ Param method the request {@ link Method} to use * @ param url URL to fetch the string at * @ param listener Listener to receive the String response * @ param errorListener Error listener, or null to ignore errors */public MultiPartStringRequest (int method, String url, Listener <String> listener, ErrorListener errorListener) {super (method, url, errorListener); mListener = listener ;} public void AddFileUpload (String param, File file) {fileUploads. put (param, file);} public void addStringUpload (String param, String content) {stringUploads. put (param, content);}/*** File to be uploaded */public Map <String, File> getFileUploads () {return fileUploads ;} /*** parameters to be uploaded */public Map <String, String> getStringUploads () {return stringUploads;} @ Override protected Response <String> parseNetworkResponse (NetworkR Esponse response) {String parsed; try {parsed = new String (response. data, HttpHeaderParser. parseCharset (response. headers);} catch (UnsupportedEncodingException e) {parsed = new String (response. data);} return Response. success (parsed, HttpHeaderParser. parseCacheHeaders (response);} @ Overrideprotected void deliverResponse (String response) {if (mListener! = Null) {mListener. onResponse (response) ;}/ *** null indicates not to upload */public String getBodyContentType () {return null ;}}
3. Usage:
/**
* Use put to upload files
* @ Param url
* @ Param files
* @ Param params
* @ Param responseListener
* @ Param errorListener
* @ Param tag
*/
Public staticvoid addPutUploadFileRequest (final Stringurl,
Final Map <String, File> files, final Map <String, String> params,
Final Listener <String> responseListener, final ErrorListenererrorListener,
Final Objecttag ){
If (null = url | null = responseListener ){
Return;
}
MultiPartStringRequest multiPartRequest = new MultiPartStringRequest (
Request. Method. PUT, url, responseListener, errorListener ){
@ Override
Public Map <String, File> getFileUploads (){
Returnfiles;
}
@ Override
Public Map <String, String> getStringUploads (){
Returnparams;
}
};
Log. I (TAG, "volley put: uploadFile" + url );
MainApplication. getVolleyQueue (). add (multiPartRequest );
}
Android supports File Upload
I did this.
Intent intent = new Intent (Intent. ACTION_GET_CONTENT );
Intent. setType ("*/*");
Intent. addCategory (Intent. CATEGORY_OPENABLE );
StartActivityForResult (Intent. createChooser (intent, "select a file to upload"), 1 );
Select a file and call
Protected void onActivityResult (int requestCode, int resultCode, Intent data ){
If (resultCode = Activity. RESULT_ OK ){
Uri uri = data. getData ();
String url = uri. toString ();
}
}
Obtain the path and call it according to the path
Public String convertCodeAndGetText (String str_filepath) {// transcode \
Try {
File file1 = new File (str_filepath );
File_name = file1.getName ();
FileInputStream in = new FileInputStream (file1 );
Byte [] buffer = new byte [(int) file1.length () + 100];
Int length = in. read (buffer );
Load = Base64.encodeToString (buffer, 0, length,
Base64.DEFAULT );
In. close ();
} Catch (FileNotFoundException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
Return load;
}
Encode a file
Does Volley provide File Upload methods? Or should I implement it myself?
I want to use the form submission method to upload text data and files at the same time. Is there an example? View Original post>
Adoption