Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Android+spring boot Select, upload and download Files

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

1 Overview

The front end android, uploads and downloads files, uses OkHttp to process requests, and the back end uses spring boot+MVC to handle upload and download requests sent by android. In fact, this is not difficult, it is a lot of strange holes, therefore, I hope to see, do not step on as painful as the author.

2 Environment win10Spring Boot 2.2.2 RELEASEIDEA 2019.3.1Android Studio 3.6RC1Tomcat 9.0.303 android3.1 preparation 3.1.1 New Project

This time, write a blog with a brand new example, so start with the new project:

3.1.2 AndroidManifest.xml

Join

Network permissions, access to read and write SD cards, and of course, permission to allow http requests.

3.1.3 build.gradle

Join

CompileOptions {sourceCompatibility = 1.8 targetCompatibility = 1.8}

This one supports JDK8.

There are also these two okhttp and conscrypt. The latest version of okhttp can be viewed here, and the latest version of conscrypt is here:

Implementation 'com.squareup.okhttp3:okhttp:4.3.1'implementation' org.conscrypt:conscrypt-android:2.2.1'3.1.4 uploads files

Manually upload some files to the AVD device to prepare for the next step of selecting and uploading files, first open the window toolbar:

When open, open Device File Explorer in the right column:

Then select the sdcard folder to upload files, other folders generally do not have permission.

3.1.5 layout

Add three button (upload / download / select file), one EditText (upload file name and download file name), and one ImageView (display downloaded image).

Drag and drop directly to change the id.

3.2 Select File 3.2.1 apply permission

First of all, apply for the permission to read and write the file dynamically (in fact, you only need the read permission to select the file, because the later downloads need write permission, so you will apply together here):

Use checkSelfPermission to check permissions. The parameter is a Context and String,String indicating the corresponding permissions. If you have this permission, it will be returned.

PackageManager.PERMISSION_GRANTED

If not, it will be returned.

PackageManager.PERMISSION_DENIED

If not, use requestPermissions () to apply. The parameter is Content,String []. Int,String [] indicates all permissions to be applied for. Int is a requestCode.

3.2.2 Intent Select File

After creating a new Intent, set the selection type, and then rewrite the onActivityResult:

This is a simplified process, because you choose pictures, you can refer to here if you choose other files.

Where path is the path to the selected file, you may ask:

String path = dir.toString () .substring (0Magneol dir.toString () .indexOf ("0") + 2) + DocumentsContract.getDocumentId (uri) .split (":") [1]

How did this come from? it's actually pieced together, because it's a picture, a simplified version of this:

(the blog is here)

3.3 upload files

Parameters are the file path and file name, and then use OkHttpClient, because it is a file, the body is MultipartBody, add a FormDataPart called file and a FormDataPart called filename. Then use execute () to send the request, and body () to get the response content. Here, it is assumed that the backend responds to a Boolean indicating whether the upload is successful or failed. If url uses a local path, note that it cannot be localhost, use private network ip, and then correspond to the backend.

3.4 download the file

The parameter is a file name, and the corresponding file and File are returned according to the file name. Here, the request body can select FormBody or MultipartBody, because this is a file name parameter. Here, the author chooses MultipartBody for unification. If you use FormBody, you only need to change the line of RequestBody to:

RequestBody body = new FormBody.Builder () .add ("filename", filename) .build ()

After you have the request body, send a request to get the response body, and then get the input stream. Then you need to determine whether it is empty or not, but you cannot directly judge it this way:

InputStream = = null

Because the back end goes like this:

The inputStream obtained from the response body is definitely not null, so you need to read it first (that is, to determine whether the file is null), delete the file if it is null, and continue to read and write to the file if it is not null.

4 Spring Boot4.1 preparation work

Use IDEA, other IDE please search for how to create a new SpringBoot project.

4.1.1 New project

Package can be jar or war, do not need to deploy then jar can, if you want to deploy, you can also change to war.

Two, one Spring Web, for MVC, etc., and a template engine for displaying views, which can be unselected if you don't need to display.

4.1.2 application.properties

As an example demo, the properties are configured directly in the application.properties. In fact, please configure the corresponding properties in the corresponding configuration file.

You need to configure the size limit of the uploaded file and the path of the uploaded folder.

4.1.3 pom.xml

You don't really need to do anything here, but if the download dependency is slow, you can set the settings.xml file like this and add:

Alimaven aliyun maven http://maven.aliyun.com/nexus/content/groups/public/ central uk central Human Readable Name for this Mirror. Http://uk.maven.org/maven2/ CN OSChina Central http://maven.oschina.net/content/groups/public/ central nexus internal nexus repository http://repo.maven.apache.org/maven2 central

For windows users, this file is available at

C:\ Users\ {username}\ .m2\ settings.xml

In the words of linux

~ / .m2/settings.xml4.2 handles uploading files

First, the corresponding post mapping path is / upload, corresponding to the path on the Android side, and then you need a MultipartFile for the file and a String for the file name. After judging whether these two are empty, create the uploaded folder if it does not exist, copy it directly if it exists, and then return a Boolean value based on the success or failure of the replication. Files.copy () is used to copy. The first InputStream is the input stream for uploading files, and the second Path is the path where the files are stored. Resolve (filename) is equivalent to the filename file in the uploaded directory. It is recommended to use logs instead of output.

4.3 processing downloaded files

If you download, you can choose to use get or post request. Here you choose post request, because the Android side is a post request. If you need to correspond to a .get request, you can initiate it from the browser.

First, get the corresponding file according to the file name, determine whether the file exists and return a ResponseEntity. You need to set content-type and body,content-type as needed. Here is the image, default .jpg or .png. If you use FileSystemResource for body, you can directly new one into body.

If the corresponding file does not exist, null is returned. Here, we need to pay attention to the judgment of the front end. We cannot directly judge whether ResponseBody is null.

5 Test 5.1 postman Test

Postman can only test whether there are problems with connection to the backend, upload, etc., and can be used to locate backend problems.

5.1.1 upload test

After setting Content-Type to multipart/form-data in Headers:

Add a file called file and a string called filename to body to represent the file name:

Send and return true.

There is an output prompt on the server:

View the folder:

5.1.2 download Test

Turn off the file parameter, keep the filename, and modify the path.

Then send it, and postman can display the picture directly:

5.2 android side test 5.2.1 upload test

Backend hint:

View the folder:

5.2.2 download Test

Enter the file name and download it directly:

The default is to put it here and change the location as needed, with write permission added:

If you can't see the file, just choose synchronize.

6 deploy to the server

The server uses tomcat and needs to modify some parts of Spring Boot.

6.1 deployment 6.1.1 change the packaging method

In pom.xml, jar is changed to war.

6.1.2 remove tomcat dependency

Pom.xml joins:

Org.springframework.boot spring-boot-starter-tomcat provided6.1.3 modifies Main

Modify the Main class to inherit SpringBootServletInitializer, overload configure (), while main () remains the same.

Before modification:

After modification:

6.1.4 modify path

This can be modified as needed, but it is not needed here. Note that @ PostMapping,@GetMapping and so on are all relative to

Tomcat/webapps/ Project /

Under the catalogue.

6.1.5 set package name

Build plus.

6.1.6 packing

6.1.7 upload to the server

The packaged files can be put under target and uploaded using scp. Here is the local tomcat, and this is the mobile war.

6.1.8 run

Open tomcat and double-click startup.bat.

In linux's words:

Cd xxxx/tomcat/bin./startup.sh6.2 test

Before testing, you need to make sure that the corresponding port is not occupied. The default is 8080, that is, if you do not change the port, you need to close the SpringBoot application while IDEA is running.

6.2.1 postman Test

For upload test, note that you need to change the path and add the name of the packaged project. You can use localhost or private network ip for ip.

The server received it, because the upload path only writes the name directly, so it will be the same path as startup.bat.

Download Test:

Output of the server:

6.2.2 android side testing

The android side needs to modify the path, plus the name of the war package.

The name of the package here is kr, just add it.

You also need to add it where you upload it, then:

Output of the server:

View the file:

7 favorite pit 7.1 permissions

Android needs read permission to read and upload files, and write permission to save files returned from the server. Add to AndroidManifest.xml:

.

This is the read and write access of external devices. Of course, you cannot access it if you join this, because you still need to apply for permission dynamically in the future for android6.0, so:

String [] permission = new String [] {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"}; if (ActivityCompat.checkSelfPermission (this,permission [0])! = PackageManager.PERMISSION_GRANTED | | ActivityCompat.checkSelfPermission (this,permission [1])! = PackageManager.PERMISSION_DENIED) {ActivityCompat.requestPermissions (this,permission,1);} 7.2 path

You need to make sure that the following paths are correct, readable, writable, etc.:

The url path cannot be wrong. The path to upload files at the front end. The back end receives the path where the front end uploads the file. The path of the file that the backend sends the front end that needs to be downloaded. The path where the front end receives the download file. 7.3 questions about http 7.3.1 stream shutdown for okhttp

If the front end is written like this, Response has been closed after it is returned in the tool class, so you need to read the input stream and then return, instead of returning a ResponseBody or InputStream to read, otherwise you will be prompted "closed".

7.3.2 http

Android P begins to disable http by default, so you can use https or allow http connections in AndroidManifest.xml:

7.3.3 Thread

The network request cannot be in the main thread, just open a new thread.

7.3.4 AVD

If there is no problem with the server and android, it may be the problem with AVD. The solution is simple: uninstall and restart AVD. Be sure to uninstall and restart.

7.4 ip

If you test locally, you can directly localhost the backend, but not localhost directly on the Android side. You can use ipconfig or ifconfig to view the private network ip and enter the private network ip.

If you test on the server and directly use the server ip.

7.5 Air judgment processing

For the front end, you should determine whether the storage path is empty, whether it is null, etc., and then pass it to the back end. For the back end, if you want to determine whether the file exists, etc., return null if it does not exist. Then you need the front end to judge the returned null. When downloading the file, although the back end returns null for the file that does not exist, the front end receives an InputStream and cannot directly judge whether it is null. You need to read it first. Then do the rest of the reading:

8 source code

Github

Code cloud

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.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report