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 to use vue+axios+lrz.js to achieve Image Compression on Wechat

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to use vue+axios+lrz.js to achieve Wechat picture compression". In daily operation, I believe many people have doubts about how to use vue+axios+lrz.js to achieve Wechat picture compression. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "how to use vue+axios+lrz.js to achieve Wechat picture compression". Next, please follow the editor to study!

Business scenario

Wechat projects are built on Vux + Axios. There are the following requirements for image upload business scenarios:

1. Upload a single picture (such as personal profile portrait, real name authentication, etc.)

2. Upload multiple pictures (such as some kind of work order record)

3. When uploading pictures, it is expected to be compressed according to the specified size.

4. To upload pictures, you can choose from the album or take photos directly.

The pit encountered

Upload pictures using Wechat JSSDK

In the previous project (mui + jquery), I used the interface of Wechat JSSDK to upload pictures, so I thought I would be able to migrate to this project quickly. It turns out that there is nothing simple about programming:

1. Compress the picture according to the specified size

The wx.chooseImage interface provided by JSSDK cannot specify the image compression size, and can only be converted to the specified size when the back-end interface obtains the image through localId.

2. Verification of API permissions of Wechat JSSDK

As long as it is a single-page application project, Wechat JSSDK injection permission verification will have this hole, and this is also associated with route patterns (hash or history). With regard to this pit, a summary will be written again. Refer to the solution [Wechat JSSDK] to solve the SDK injection permission to verify that Android is normal, and config fail appears in IOS.

After weighing that the web page may need to upload files on browsers other than Wechat, Gu later gave up using Wechat's JSSDK interface to upload pictures.

Android version of Wechat, input onchange event does not trigger

Many people have stepped on this hole in the circle. It is normal to test on PC. After release, Wechat will be able to select files when uploading, but there will be no effect afterwards. Log tracking and api in the background are not called, so it is determined that the onchange event of input has not been triggered.

Solution, change the accept property of input:

Change the above code to:

If you are not allowed to choose from the album, you can only take pictures and add capture= "camera":

(note: if the scene supports selecting or taking pictures from albums, the test found that some models have returned to the home page after taking pictures. Haha, it may also be caused by other factors, which have not been studied in depth.

Use Lrz.js to compress pictures

At present, the size of the image file taken by the mobile phone is usually 3-4m, which will be a waste of traffic and take up the storage space of the server if you do not compress the image during the upload (look forward to another discussion on uploading the original image). If it can be compressed at the front end, it must be the most ideal solution. On the other hand, lrz.js provides a compression scheme for front-end image files, and can specify the size of compression. Measured: for image files of about 3m, the size of the uploaded file compressed according to the width of 450px is about 500kb, and the upload time is less than 2s.

The core source code is as follows:

SelectImgs () {let file = this.$refs.file.files [0] lrz (file, {width: 450, fieldName: 'file'}). Then ((rst) = > {var xhr = new XMLHttpRequest () xhr.open (' POST', 'http://xxx.com/upload') xhr.onload = () = > {if (xhr.status = 200 | xhr.status = 304) {/ / whatever error is thrown by the backend Will go here try {/ / if the backend runs abnormally, the resolution will be successful, otherwise the resolution will not succeed let resp = JSON.parse (xhr.responseText) console.log ('response:', resp)} catch (e) {this.imageUrl = xhr.responseText} / / add the parameter rst.formData.append ('folder') 'wxAvatar') / / saved folder rst.formData.append (' base64', rst.base64) / / trigger upload xhr.send (rst.formData) return rst})}

The complete code for a single image upload component is as follows (Note: the icon icon uses the svg-icon component):

+ {{text}} import lrz from 'lrz'export default {props: {text: String, / / compressed size. Default width is 450px size: {type: Number, default: 450}}, data () {return {img: {name:', src:''}, uploadUrl: 'http://ff-ff.xxx.cn/UploaderV2/Base64FileUpload', ImageUrl:''}}, watch: {imageUrl (val, oldVal) {this.$emit ('input', val)}, value (val) {this.imageUrl = val}}, mounted () {this.imageUrl = this.value}, methods: {/ / Select picture selectImgs () {let file = this.$refs.file.files [0] lrz (file, {width: this.size FieldName: 'file'}) .then ((rst) = > {var xhr = new XMLHttpRequest () xhr.open (' POST', this.uploadUrl) xhr.onload = () = > {if (xhr.status = 200 | | xhr.status = 304) {/ / whatever error is thrown by the backend Will go here try {/ / if the backend runs abnormally, the resolution will be successful, otherwise the resolution will not succeed let resp = JSON.parse (xhr.responseText) console.log ('response:', resp)} catch (e) {this.imageUrl = xhr.responseText} / / add the parameter rst.formData.append ('folder') This.folder) / / saved folder rst.formData.append ('base64', rst.base64) / / trigger upload xhr.send (rst.formData) return rst})}, / / remove remove () {margin-top ='} .imgUploader {margin-top: 0.5rem .file-item {float: left; position: relative; width: 100px; text-align: center; left: 2remt; img {width: 100px; height: 100px; border: 1px solid # ececec;}. File-remove {position: absolute; right: 0px; top: 4px; width: 14px; height: 14px; color: white; cursor: pointer; line-height: 12px; border-radius: 100%; transform: rotate (45deg) Background: rgba (0,0,0,0.5);} &: hover. File-remove {display: inline;}. File-name {margin: 0; height: 40px; word-break: break-all; font-size: 14px; overflow: hidden; text-overflow: ellipsis; display:-webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;} .add {width: 100px; height: 100px; float: left Text-align: center; line-height: 100px; font-size: 30px; cursor: pointer; border: 1px dashed # 40c2da; color: # 40c2da; position: relative; background: # ffffff; .icon {font-size: 1.4rem; color: # 7dd2d9; vertical-align:-0.25rem9;} .text {font-size: 1.2rem; color: # 7dd2d9; vertical-align: 0.25rem } input [type= "file"] {position: absolute; left: 0; top: 0; width: 100%; height: 100%; border: 1px solid # 000; opacity: 0;}

Back-end image storage and processing

The processing of images by the back-end api is essential. You need to convert the base64 string submitted by the front end into the image format and store it in the specified folder. The API returns the Url path of the image. The processing logic of images at the back end of each project is inconsistent, and the following scheme is for reference only (we have built an independent file storage site using asp.net MVC).

The core source code is as follows:

/ base64 upload image file / corresponding folder location / picture file base64 string / public ActionResult Base64FileUpload (string folder, string base64) {var context = System.Web.HttpContext.Current; context.Response.ClearContent (); / / because when the frontend calls, you need to do cross-domain processing context.Response.AddHeader ("Access-Control-Allow-Origin", "*") Context.Response.AddHeader ("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); context.Response.AddHeader ("Access-Control-Allow-Headers", "content-type"); context.Response.AddHeader ("Access-Control-Max-Age", "30"); if (context.Request.HttpMethod.Equals ("OPTIONS")) {return Content (");} var resultStr = base64.Substring (base64.IndexOf (", ") + 1) / / it is important that byte [] bytes = Convert.FromBase64String (resultStr); var fileName = Guid.NewGuid (). ToString () + ".png"; if (folder.IsEmpty ()) folder = "folder"; / / Local upload string root = string.Format ("/ Resource/ {0} /", folder); string virtualPath = root + fileName; string path = Server.MapPath ("~" + virtualPath) / / create folder if (! Directory.Exists (Path.GetDirectoryName (path)) {Directory.CreateDirectory (Path.GetDirectoryName (path));} System.IO.MemoryStream ms = new System.IO.MemoryStream (bytes); / / convert to MemoryStream object System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap (ms) that cannot be resized; bitmap.Save (path, System.Drawing.Imaging.ImageFormat.Png); / / Save to server path ms.Close () / / close the current stream and release all the resources associated with it, return Content (Net.Url + virtualPath); / / return the file path} so that the study on "how to use vue+axios+lrz.js to achieve image compression on Wechat" is over. I hope to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Internet Technology

Wechat

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

12
Report