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

How does SpringBoot+ WeChat Mini Programs realize the function of uploading and downloading files

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces SpringBoot+ WeChat Mini Programs how to achieve file upload and download function, the article is very detailed, has a certain reference value, interested friends must read it!

1. File upload 1.1 backend

1.1.1 introducing Apache Commons FIleUpload component dependencies

Commons-fileupload commons-fileupload 1.3.3 commons-io commons-io 2.2

1.1.2 set upload file size limit

Add the following parameters to the application.yml (properties that some people may use depending on the individual situation) configuration file:

1.1.3 create a controller

The back-end part is very simple, is to achieve file upload, this learned SpringMVC on the line.

@ ApiOperation ("File upload") @ PostMapping ("/ upload") public String upload (HttpServletRequest request, @ RequestParam ("file") MultipartFile file) throws IOException {if (! file.isEmpty ()) {/ / upload file path / / String path= request.getServletContext () .getRealPath ("/ uploadFiles/"); String path= "E:/upload" / / get the uploaded file name String fileName = file.getOriginalFilename (); File filePath = new File (path + File.separator + fileName); System.out.println (filePath); / / if the file directory does not exist, create a directory if (! filePath.getParentFile () .exists ()) {filePath.getParentFile () .mkdirs () } / / Save the uploaded file to a target file file.transferTo (filePath); return "success";} return "fail";}

For convenience here, I directly use the absolute path, which is not allowed in the production environment.

1.2 the front part of Mini Program

The wx.uploadFile (OBJECT) API uploads local resources to the developer's server, and the client initiates a Post request for HTTPS, where content-type is multipart/form-data. You need to obtain the resources on the local (mobile phone) before uploading, that is, you should call other APIs to obtain the file resources to be uploaded before using wx.uploadFile (OBJECT). For example, call API wx.chooseImage () to obtain the temporary file path to the local image resources, and then upload the local resources to the specified server through the wx.uploadFile (OBJECT) API. The properties of the wx.uploadFile () interface are shown in the following table.

Sample code of the official website:

Wx.chooseImage ({success (res) {const tempFilePaths = res.tempFilePaths wx.uploadFile ({url: 'https://example.weixin.qq.com/upload', / / is only an example Non-real interface address filePath: tempFilePaths [0], name: 'file', formData: {' user': 'test'}, success (res) {const data = res.data / / do something}})})

The real front-end code is as follows:

Pages/uploadFile/uploadFile.wxml

Choose to upload a file

Pages/uploadFile/uploadFile.js

/ / index.js// gets the application instance var app = getApp () Page ({data: {}, / / event handler function upfile: function () {console.log ("--bindViewTap--") wx.chooseImage ({success: function (res) {var tempFilePaths = res.tempFilePaths wx.uploadFile ({url: 'http://127.0.0.1:8001/file/upload',) Header: {"Content-Type": "multipart/form-data"}, filePath: tempFilePaths [0], name: 'file', formData: {}, success (res) {console.log (res.data) }})}})}, onLoad: function () {}}) 1.3 to achieve the effect

After compilation:

Click to upload a file and choose a random picture

As you can see, both the front-end and back-end project consoles have corresponding output.

Then go to the corresponding path to find the file we just uploaded.

2. Download 2.1 backend part of the file

Here depends on and sets the size of the uploaded file is the same as the uploaded part, do not repeat.

2.1.1 Controller

@ ApiOperation ("file download") @ GetMapping ("download") public ResponseEntity download (HttpServletRequest request,@RequestParam ("file") String fileName) throws IOException {/ / download file path String path= "E:/upload"; / / build the file object to be downloaded File file = new File (path + File.separator + fileName); / / set the response header HttpHeaders headers=new HttpHeaders () / / download the file name displayed to solve the problem of garbled Chinese names String downloadFileName=new String (fileName.getBytes ("UTF-8"), "ISO-8859-1"); / / notify the browser to open the file headers.setContentDispositionFormData ("attachment", downloadFileName) by download (attachment) / / define the returned file data headers.setContentType (MediaType.APPLICATION_OCTET_STREAM) as binary stream data (the most common file download); / / use the ResponseEntity object encapsulation of the spring mvc framework to return the download data return new ResponseEntity (FileUtils.readFileToByteArray (file), headers, HttpStatus.OK);} 2.2 the front end of Mini Program

Wx.downloadFile (Object object) downloads file resources to the local (mobile phone). The client directly initiates a HTTPS GET request that returns the local temporary path to the file. Because it is a temporary path, which means that the user will not go to the real file directory, you should do the follow-up work immediately after downloading to the temporary path, such as setting the temporary picture as the avatar, or saving the temporary file to the specified directory of the phone through another interface. The wx.downloadFile (Object object) parameter is shown in the table.

Sample code of the official website:

The downloaded front-end code is as follows:

Two functions are implemented here, one is to set the downloaded picture as the avatar, and the other is to save the picture to the local mobile phone.

Pages/downloadFile/downloadFile.wxml

{{userInfo.nickName}} download the image above

Pages/downloadFile/downloadFile.js

/ / index.js// gets the application instance var app = getApp () Page ({data: {motto: 'Hello World', userInfo: {}, avatar:null}, / / event handler function dian: function () {console.log ("--bindViewTap--") var that = this Wx.downloadFile ({/ / url:' https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3018968254,2801372361&fm=26&gp=0.jpg', url:' http://127.0.0.1:8001/file/download?file=ymwtyNjpeZq645b1d185a17eaa9a65398443fbc4f8dd.jpg', type: 'image' Success: function (res) {console.log (res) that.setData ({avatar:res.tempFilePath})})} OnLoad: function () {console.log ('onLoad') var that = this / / call the method of the application instance to obtain global data app.getUserInfo (function (userInfo) {/ / update data that.setData ({userInfo:userInfo})})} Dian2: function () {wx.downloadFile ({url:' http://127.0.0.1:8001/file/download?file=ymwtyNjpeZq645b1d185a17eaa9a65398443fbc4f8dd.jpg', success: function (res) {console.log (res)) Var rr = res.tempFilePath; wx.saveImageToPhotosAlbum ({filePath: rr, success (res) {wx.showToast ({title: 'saved successfully', icon: 'success', duration: 2000})

The wx.downloadFile () interface is called in the function dian (). If the download is successful, the picture will be saved in res.tempFilePath, and the res.tempFilePath will be set as the avatar. In the function dian2, the downloaded picture is saved to the system photo album through the wx.saveImageToPhotosAlbum () interface.

2.3 achieve effect

This picture is downloaded directly from the server. You can click to download it and save it locally.

At this point, the uploading and downloading of files are basically done. In fact, most of them are back-end things, and there is no big problem when the interface is written. If you don't rest assured, you can test it with swagger first.

The above is all the contents of the article "how to upload and download files by SpringBoot+ WeChat Mini Programs". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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

Development

Wechat

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

12
Report