In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains the "Android how to use Retrofit2 to achieve multi-file upload", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "how to use Retrofit2 in Android to achieve multi-file upload" bar!
1. Experimental effect
The picture received by the Server
2. Actual combat on Server side
The Server side is responsible for receiving and saving the pictures uploaded from the client and providing the ability to access the pictures. Server has many technologies to achieve. Python, as a language with a powerful third-party library, has many web service frameworks, such as Flask,Django. The author uses the Flask framework, Flask is a micro-framework, the realization of small functions is very convenient, the author to achieve multi-file upload function, the program is no more than 30 lines.
Let's take a look at the details below.
2.1 Environmental installation
The author uses the Python version 3.4, you can go to Python3.4 to choose to download the version suitable for your system. Please search for the complete installation of Python tutorials.
After the Python installation is completed, you need to install the server-side program dependent library. Install via pip:
Pip install Flask pip install werkzeug
2.2 Program implementation
The first step is to introduce dependent libraries:
From flask import Flask,request,send_from_directory,jsonify import os from werkzeug import secure_filename
In this lab, you need to upload files, and you need to limit the file type and file name of the uploaded file to prevent some programs that damage the server from running, and some illegal file names such as:
Filename = ".. / home/username/.bashrc"
If hackers can manipulate such files, it will be a fatal blow to the server system. Therefore, werkzeug provides secure_filename to legally verify the file name of the uploaded file.
Determine whether the file suffix is legal
ALLOWED_EXTENSIONS=set (['png','jpg','jpeg','gif']) def allowed_file (filename): return'. In filename and filename.rsplit ('.', 1) [1] in ALLOWED_EXTENSIONS
The function code for receiving uploaded files is as follows:
App.route ('/ upload',methods= ['POST']) def upload_file (): if request.method=='POST': for k in request.files: file = request.files [k] image_urls = [] if file and allowed_file (file.filename): filename=secure_filename (file.filename) file.save (os.path.join (app.config [' IMAGE_FOLDER'], filename) image_urls.append ("images/%s"% filename) return jsonify ({"code": 1) "image_urls": image_urls})
Flask supports HTTP request methods such as GET,POST,PUT,DELETE, which is decorated with decorators, similar to the annotation concept in Java. / upload is the relative address of the client request, and the request method is limited to POST. According to the request built-in object, you can access the file sent by the client, check the file and save it locally, where image_urls is the array of relative addresses of the uploaded image. * * return the address of the image to the client in json format.
The complete Server code is as follows:
From flask import Flask,request,send_from_directory,jsonify import os from werkzeug import secure_filename app = Flask (_ _ name__) app.config ['IMAGE_FOLDER'] = os.path.abspath ('.') +'\ images\\ 'ALLOWED_EXTENSIONS=set ([' png','jpg','jpeg','gif']) def allowed_file (filename): return'. In filename and filename.rsplit ('.', 1) [1] in ALLOWED_EXTENSIONS @ app.route ('/ upload',methods= ['POST']) def upload_file (): if request.method=='POST': for k in request.files: file = request.files [k] print (file) image_urls = [] if file and allowed_file (file.filename): filename=secure_filename (file.filename) file.save (os.path.join (app.config [' IMAGE_FOLDER']) Filename) image_urls.append ("images/%s"% filename) return jsonify ({"code": 1, "image_urls": image_urls}) # allows file mapping access Otherwise, you can only access the file @ app.route ("/ images/", methods= ['GET']) def images (imgname): return send_from_directory (app.config [' IMAGE_FOLDER']) in the static folder by default. Imgname) if _ _ name__ = = "_ _ main__": # detect whether if not os.path.exists exists in IMAGE_FOLDER (app.config ['IMAGE_FOLDER']): os.mkdir (app.config [' IMAGE_FOLDER']) app.run ("192.168.1.102", debug=True)
Here is a tip: you can use Postman to test after writing the Server-side code, and then develop the client program after the test is successful.
3. Client development
Because it involves the upload of files, the author takes the picture as an example to upload the experiment. In addition to the Retrofit, the picture upload also needs to select the picture. The author recommends a picture selection library ImagePicker that imitates Wechat.
3.1 add dependent libraries
Picture loading library the author likes to use Glide
Compile 'com.squareup.retrofit2:retrofit:2.1.0' compile' com.squareup.retrofit2:converter-gson:2.1.0' compile 'com.github.bumptech.glide:glide:3.7.0' compile' com.lzy.widget:imagepicker:0.4.1'
3.2 Program implementation
If you have not come into contact with Retrofit 2, you can come to my blog Retrofit tutorial to learn.
Retrofit2 is a request library that supports RESTful API. In fact, it is only an encapsulation of API request mode. The real network request is sent by OkHttp.
Retrofit2 typically defines a ServiceGenerator class that is used to dynamically generate Retrofit objects.
Public class ServiceGenerator {public static final String API_BASE_URL = "http://192.168.1.102:5000/"; private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder (); private static Retrofit.Builder builder = new Retrofit.Builder () .baseUrl (API_BASE_URL) .addConverterFactory (GsonConverterFactory.create ()); public static S createService (Class serviceClass) {Retrofit retrofit = builder.client (httpClient.build ()). Build (); return retrofit.create (serviceClass);}}
The specific API operation is operated by FlaskClient interface.
Public interface FlaskClient {/ / upload picture @ Multipart @ POST ("/ upload") Call uploadMultipleFiles (@ PartMap Map files);}
To upload a file, you need to use the @ Multipart keyword annotation. @ POST indicates that the HTTP request method is POST,/upload, which is the relative address of the request server, uploadMultipleFiles is a custom method name, and the parameter is Map files, that is, a Map object composed of multiple files. @ PartMap indicates that this is a multi-file upload. If a single file can be uploaded using @ Part MultipartBody.Part file, the return type of the method defaults to Response, because we have developed the server. So we know that the format of the returned data on the server side is Json, so we create a new UploadResut class for the returned data format.
Public class UploadResult {public int code; / / 1 public List image_urls;}
The interface layout is shown in the figure:
Click the Upload button to perform the upload operation. The core method is:
Public void uploadFiles () {if (imagesList.size () = = 0) {Toast.makeText (MainActivity.this, "cannot not choose a picture", Toast.LENGTH_SHORT). Show (); return;} Map files = new HashMap (); final FlaskClient service = ServiceGenerator.createService (FlaskClient.class); for (int I = 0; I < imagesList.size (); iTunes +) {File file = new File (imagesList.get (I) .path) Files.put ("file" + I + "\"; filename=\ "+ file.getName (), RequestBody.create (MediaType.parse (imagesList.get (I) .mimeType), file));} Call call = service.uploadMultipleFiles (files) Call.enqueue (new Callback () {@ Override public void onResponse (Call call, Response response) {if (response.isSuccessful () & & response.body (). Code = = 1) {Toast.makeText (MainActivity.this, "upload successfully", Toast.LENGTH_SHORT) .show () Log.i ("orzangleli", "- uploaded successfully--"); Log.i ("orzangleli", "basic address:" + ServiceGenerator.API_BASE_URL) Log.i ("orzangleli", "relative address of the picture:" + listToString (response.body (). Image_urls,',')); Log.i ("orzangleli", "- END---") } @ Override public void onFailure (Call call, Throwable t) {Toast.makeText (MainActivity.this, "upload failed", Toast.LENGTH_SHORT). Show ();}});}
The parameter of building the method of uploading multiple files is more critical. MediaType.parse (imagesList.get (I) .mimeType) obtains the mimeType of the image, which, if specified incorrectly, may cause the upload to fail.
Map files = new HashMap (); final FlaskClient service = ServiceGenerator.createService (FlaskClient.class); for (int I = 0; I < imagesList.size (); iTunes +) {File file = new File (imagesList.get (I) .path); files.put ("file" + I + "\"; filename=\ "+ file.getName (), RequestBody.create (MediaType.parse (imagesList.get (I) .mimeType), file);}
The second argument to the onResponse method of the anonymous callback class that integrates the Callback excuse is the server response, which returns an object of type UploadResult by accessing the body () method, and then you can access the uploaded picture by combining ServiceGenerator.API_BASE_URL and response.body (). Image_urls each item.
Thank you for reading, the above is "how to use Retrofit2 in Android to achieve multi-file upload" content, after the study of this article, I believe you have a deeper understanding of how to use Retrofit2 to achieve multi-file upload in Android, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.