Introduction to Web Uploader
WebUploader is a simple modern file upload component mainly HTML5 and supplemented by FLASH developed by Baidu WebFE (FEX) team. In modern browsers, we can give full play to the advantages of HTML5, while not abandoning mainstream IE browsers, and continue to use the original FLASH runtime, and are compatible with IE6+, iOS 6+, android 4+. The two sets of running time, the same call method can be selected by users at will. The use of large file fragmentation concurrent uploading greatly improves the efficiency of file uploading.
Here we use an example from the official website to upload our personal avatar.
Our focus is on how to upload files using WebUploader in Spring Boot project, so we can directly implement a simple function for reference only.
Here is an example downloaded from the official website: image upload function with cropping.
We use examples to remodel avatar uploads in the project.
The effect looks like this:
First, let's remodel our WebUploader sample code.
The following are some of the codes in my project:
(function( factory ) { if ( !window.jQuery ) { alert('jQuery is required.') } jQuery(function() { factory.call( null, jQuery ); });})(function( $ ) {// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Error( 'WebUploader does not support the browser you are using.' ); } // hook, // Crop before the file starts uploading. Uploader.register({ 'before-send-file': 'cropImage' }, { cropImage: function( file ) { var data = file._cropData, image, deferred; file = this.request( 'get-file', file ); deferred = _.Deferred(); image = new _.Lib.Image(); deferred.always(function() { image.destroy(); image = null; }); image.once( 'error', deferred.reject ); image.once( 'load', function() { image.crop( data.x, data.y, data.width, data.height, data.scale ); }); image.once( 'complete', function() { var blob, size; // Mobile UC / qq browser in image-free mode // ctx.getImageData will report an Exception when processing large images // INDEX_SIZE_ERR: DOM Exception 1 try { blob = image.getAsBlob(); size = file.size; file.source = blob; file.size = blob.size; file.trigger( 'resize', blob.size, size ); deferred.resolve(); } catch ( e ) { console.log( e ); // If there is an error, continue directly and let it upload the original image deferred.resolve(); } }); file._info && image.info( file._info ); file._meta && image.meta( file._meta ); image.loadFromBlob( file.source ); return deferred.promise(); } }); return { init: function( selectCb ) { uploader = new Uploader({ pick: { id: '#filePicker', multiple: false }, // Set how to generate thumbnails. thumb: { quality: 70, // Zoom in allowMagnify: false, // Whether to use crop mode. If this is used, blank content can be avoided. crop: false }, // Disable chunked transmission, which is enabled by default. chunked: false, // Disable compression function before upload because it will be manually cropped. compress: false, // fileSingleSizeLimit: 2 * 1024 * 1024, server: 'StudentImgFileUpload', swf: $.trim($("#BASE_URL").val()) + '/static/webuploader/Uploader.swf', fileNumLimit: 1, // Only image files are allowed. accept: { title: 'Images', // extensions: 'gif,jpg,jpeg,bmp,png', // mimeTypes: 'image/*' extensions: 'jpg,jpeg,png', // Solve WebUploader chrome Click the upload file selection box to delay a few seconds before the response will be slow mimeTypes: 'image/jpg,image/jpeg,image/png' //Modify this line} //formData: {"Authorization": localStorage.token}, //Extra parameters are passed, you can not have //chunked: true, //Shash// chunkSize: 10 * 1024 * 1024, //Shash size specifies // threads:1, //Number of threads// disableGlobalDnd: true //Disable drag// onError: function() { // var args = [].slice.call(arguments, 0); // alert(args.join('/n')); // } }); uploader.on('fileQueued', function( _file ) { file = _file; uploader.makeThumb( file, function( error, src ) { if ( error ) { alert('can't preview'); return; } selectCb( src ); }, FRAME_WIDTH, 1 ); // Note that the height value here is 1, which is regarded as 100%. }); /** * Verify file format and file size*/ uploader.on("error", function (type) { if (type == "Q_TYPE_DENIED") { showInfo("Please upload JPG, JEPG, PNG, format files"); } }); // The file upload is successful, add a successful class to the item, and mark the upload success with style. uploader.on( 'uploadSuccess', function( file ) { showInfo("uploadSuccess"); }); // The file upload fails, showing an upload error. uploader.on( 'uploadError', function( file ) { showInfo("upload failed"); }); }, crop: function( data ) { var scale = Croper.getImageSize().width / file._info.width; data.scale = scale; file._cropData = { x: data.x1, y: data.y1, width: data.width, height: data.height, scale: data.scale }; }, upload: function() { uploader.upload(); } } })();// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- img'); var btn = $('.upload-btn'); var isBase64Supported, callback; $image.cropper({ aspectRatio: 4 / 4, preview: ".img-preview", done: function(data) { // console.log(data); } }); function srcWrap( src, cb ) { // we need to check this at the first time. if (typeof isBase64Supported === 'undefined') { (function() { var data = new Image(); var support = true; data.onload = data.onerror = function() { if( this.width != 1 || this.height != 1 ) { support = false; } } data.src = src; isBase64Supported = support; })(); } if ( isBase64Supported ) { cb( src ); } else { // otherwise we need server support. // convert base64 to a file. // $.ajax('', { // method: 'POST', // data: src, // dataType:'json' // }).done(function( response ) { // if (response.result) { // cb( response.result ); // } else { // alert("preview error"); // } // }); } } btn.on('click', function() { callback && callback($image.cropper("getData")); return false; }); return { setSource: function( src ) { // Handle base64 not supported. // Generally occurs in ie6-ie8 srcWrap( src, function( src ) { $image.cropper("setImgSrc", src); }); container.removeClass('webuploader-element-invisible'); return this; }, getImageSize: function() { var img = $image.get(0); return { width: img.naturalWidth, height: img.naturalHeight } }, setCallback: function( cb ) { callback = cb; return this; }, disable: function() { $image.cropper("disable"); return this; }, enable: function() { $image.cropper("enable"); return this; } } } } })();// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Uploader.crop(data); Uploader.upload(); }); });// -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------There are also some codes for the page:
Here is the code for the Controller part:
@RequestMapping(value="/student/StudentImgFileUpload", method=RequestMethod.POST) @ResponseBody String studentImgFileUpload(@RequestParam MultipartFile file, HttpServletRequest request){ logger.info("Student avatar upload...") //Get the file name String originalFilename = file.getOriginalFilename() logger.info("Upload file name:" + originalFilename) String realPath = request.getServletContext().getRealPath("/public/student/") String uploadFileName = System.currentTimeMillis()+"_"+ originalFilename logger.info("Get upload path: " + realPath + ", the uploadFileName) boolean flag = true //Merge files RandomAccessFile raFile = null BufferedInputStream inputStream = null try{ File dirFile = new File(realPath, uploadFileName) //Open the target file in a read-write manner raFile = new RandomAccessFile(dirFile, "rw") raFile.seek(raFile.length()) inputStream = new BufferedInputStream(file.getInputStream()) byte[] buf = new byte[1024] int length = 0 while ((length = inputStream.read(buf)) != -1) { raFile.write(buf, 0, length) } }catch(Exception e){ flag = false logger.info("Upload error:" + e.getMessage()) throw new IOException(e.getMessage()) } finally{ try { if (inputStream != null) { inputStream.close() } if (raFile != null) { raFile.close() } } catch(Exception e){ flag = false logger.info("Upload error:" + e.getMessage()) throw new IOException(e.getMessage()) } } }This simply implements the function of using WebUploader for file upload in Spring Boot project.
Summarize
The above is the Spring Boot introduced to you by the editor. It uses WebUploader to upload files. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!