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 realize the upload function of springboot with progress bar

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail how to realize the upload function of springboot with progress bar. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

The details are as follows:

I. explanation

Recently, I want to upload files. I have been looking for a comprehensive example on the Internet for a long time. I would like to record it and share it with you.

1. File upload interface can be implemented according to springboot default or commons-fileupload component. In this example, springboot default file upload 2. 0 is used. Finally, there are examples of commons-fileupload component interfaces.

two。 Focus on the front-end JS implementation (you can also use ajax upload), with reference to a large number of uploaded files on the Internet to display progress bars, blogs and technical solutions, and make a unified summary here to facilitate subsequent use

3. This is just an example, and we can improve it according to our actual needs.

Second, front-end code

File upload

0KB/s

Var fileBtn = $("input [name=file]"); var processBar= $("# progressBar"); var uploadBtn=$ ("input [name=upload]"); var canelBtn=$ ("input [name=cancelUpload]"); var ot;// upload start time var oloaded;// uploaded file size fileBtn.change (function () {var fileObj = fileBtn.get (0). Files [0]; / / js gets file object if (fileObj) {var fileSize = getSize (fileObj.size) $("label [name=upfileName]"). Text ('file name:' + fileObj.name); $("label [name=upfileSize]"). Text ('file size:' + fileSize); $("label [name=upfileType]") .text ('file type:' + fileObj.type); uploadBtn.attr ('disabled', false);}}) / / uploadBtn.click (function () {/ / progress bar zeroing setProgress (0); / upload button disables $(this) .attr ('disabled', true); / / progress bar displays showProgress (); / / upload file uploadFile ();}); function uploadFile () {var url = "/ to/upload" Var fileObj= fileBtn.get (0) .files [0]; if (fileObj==null) {alert ("Please select a file"); return;} / / FormData object var form = new FormData (); form.append ('file', fileObj); / / File object / / XMLHttpRequest object var xhr = new XMLHttpRequest (); / / true is asynchronous processing xhr.open (' post', url, true) / / start upload execution method xhr.onloadstart = function () {console.log ('start upload') ot = new Date (). GetTime (); / / set upload start time oloaded = 0 false / uploaded file size 0}; xhr.upload.addEventListener ('progress', progressFunction, false); xhr.addEventListener ("load", uploadComplete, false); xhr.addEventListener ("error", uploadFailed, false) Xhr.addEventListener ("abort", uploadCanceled, false); xhr.send (form); function progressFunction (evt) {debugger; if (evt.lengthComputable) {var completePercent = Math.round (evt.loaded / evt.total * 100) +'%'; processBar.width (completePercent); processBar.text (completePercent); var time = $("# time") Var nt = new Date (). GetTime (); / / get the current time var pertime = (nt-ot) / 1000; / / calculate the time difference between the last time the method was called and now, in s ot = new Date () .getTime (); / / re-assign the time to calculate var perload = evt.loaded-oloaded next time / / calculate the size of the uploaded file in this part, in b oloaded = evt.loaded; / / re-assign the uploaded file size / / upload speed calculation var speed = perload/pertime;// unit b var bspeed s size = speed; var units = 'bram if / unit name if (speed/1024 > 1) {size = speed/1024 Units = 'KUnip slots;} if (speed/1024 > 1) {speed = speed/1024; units =' M speed.toFixed slots;} speed = speed.toFixed (1); / / remaining time var resttime = ((evt.total-evt.loaded) / bspeed) .tofixed (1) $("# showInfo") .html (speed+units+', remaining time:'+ resttime+'s');}} / / callback function uploadComplete (evt) {uploadBtn.attr ('disabled', false); console.log (' upload complete')} after uploading successfully / / callback function uploadFailed (evt) {console.log ('upload failed' + evt.target.responseText);} / / terminate upload function cancelUpload () {xhr.abort () } / / callback function uploadCanceled (evt) {console.log ('upload cancelled, upload cancelled by user or browser disconnected:' + evt.target.responseText);} canelBtn.click (function () {uploadBtn.attr ('disabled', false); cancelUpload ();})} function getSize (size) {var fileSize =' 0KB' If (size > 1024 * 1024) {fileSize = (Math.round (size / (1024 * 1024)). ToString () + 'MB';} else {fileSize = (Math.round (size / 1024)). ToString () +' KB';} return fileSize;} function setProgress (w) {processBar.width (w +'%');} function showProgress () {processBar.parent (). Show () } function hideProgress () {processBar.parent () .hide ();}

3. Component encapsulation of the uploaded code

UploadCommon.js

/ * Common component for uploading files * * @ param url upload address * @ param processBar progress bar page component * @ param speedLab displays the page component obtained by the upload speed Label jquery * @ param uploadBtn upload button jquery gets the page component * @ param cancelBtn cancel the upload button jquery gets the page component * @ param callBack the callback function after the upload is completed Can not send * @ author * @ returns * / function UploadCommon (url, processBar, speedLab, uploadBtn, cancelBtn, callBack) {function init () {/ / each callback monitor upload start time var startTime = null / / uploaded file size var oloaded = null var xhr = new XMLHttpRequest () function setProgress (w) {processBar.width (w +'%') ProcessBar.text (w +'%') } function progressMonitor (evt) {if (evt.lengthComputable) {var completePercent = Math.round (evt.loaded / evt.total * 100) setProgress (completePercent) var nowTime = new Date () .getTime () / / calculates the time difference between the last call to the method and now, in s var pertime = (nowTime-startTime) / 1000 / / re-assignment time Used to calculate the next time startTime = new Date () .getTime () / calculate the size of the uploaded file in this part, in b var perload = evt.loaded-oloaded / / re-assign the size of the uploaded file Use the following calculation oloaded = evt.loaded / / upload speed calculation Unit var speed = perload / pertime var bspeed = speed / / Unit name var units = 'bit/s'if (speed / 1024 > 1) {speed = speed / 1024 units =' Kb/s'} if (speed / 1024 > 1) {speed = speed / 1024 units = 'Mb/s'} Speed = speed.toFixed (1) / / remaining time var resttime = ((evt.total-evt.loaded) / bspeed) .tofixed (1) speedLab.html (speed + units +') Remaining time:'+ resttime +'s'}} / / callback function uploadComplete (evt) {uploadBtn.attr ('disabled') after uploading successfully False) var status = evt.currentTarget.status if (status = = 401) {alert ('please log in before uploading') return} if (status = = 403) {alert ('No permission operation') return} if (status! = 200) {alert ('upload exception Error code'+ status) return} var response=JSON.parse (evt.currentTarget.response) if (response. upload handling exception 200') {alert ('upload handling exception' + response.msg) return} console.log ('upload successful') if (callBack! = null & & typeof callBack! = 'undefined') {callBack ()}} / / callback function uploadFailed (evt) {alert ('upload processing failed' + evt.target.responseText)} / / terminate upload function cancelUpload () {xhr.abort ()} / / callback function uploadCanceled (evt) {alert ('file upload terminated:' + evt.target.responseText)} / / add cancel upload event cancelBtn.click (function () {uploadBtn.attr ('disabled') False) cancelUpload () }) this.uploadFile = function (formData) {/ / upload button disables uploadBtn.attr ('disabled', true) SetProgress (0) / / true is asynchronous processing xhr.open ('post', url True) / / upload start execution method xhr.onloadstart = function () {console.log ('start upload') / / set upload start time startTime = new Date () .getTime () / / the uploaded file size is 0 oloaded = 0} xhr.upload.addEventListener ('progress', progressMonitor, false) xhr.addEventListener ("load", uploadComplete) False) xhr.addEventListener ("error" uploadFailed, false) xhr.addEventListener ("abort", uploadCanceled, false) xhr.send (formData) } this.setProgressValue=function (w) {processBar.width (w +'%') processBar.text (w +'%')}} return new init ()}

Call

$(document) .ready (function () {var addVersionBtn=$ ('# addVersionBtn') / / var cancelUploadBtn=$ ('# cancelUploadBtn') / / var fileInput=$ ("# filewareFile") / / var processBar = $("# progressBar"); / / p var fileNameLab=$ ("label [name=upfileName]") / / var fileSizeLab=$ ("label [name=upfileSize]") / /. Var fileTypeLab=$ ("label [name=upfileType]") / /. Var speedLab=$ ("# showSpeed") / / var url='/api/file' / / get file upload instance var upload=UploadCommon (url,processBar,speedLab,addVersionBtn,cancelUploadBtn,initPageInfo) / / File selection box change event fileInput.change (function () {var fileObj = fileInput.get (0). Files [0]; / / js get file object if (fileObj) {var fileSize = getSize (fileObj.size) FileNameLab.text ('file name:' + fileObj.name); fileSizeLab.text ('file size:' + fileSize); fileTypeLab.text ('file type:' + fileObj.type); addVersionBtn.attr ('disabled', false);}}) / / Click to upload firmware event addVersionBtn.click (function () {var versionInfo=$ ('# version'). Val () var file= fileInput.get (0). Files [0] var strategyInfo=$ ('# versionType') .val () if (file==null) {alert ("firmware file cannot be empty") return} if (versionInfo=='') {alert ("version number cannot be empty") Return} if (strategyInfo=='') {alert ("upgrade policy cannot be empty") return} / / create submission data var formData = new FormData () FormData.append ('firmFile', fileInput.get (0). Files [0]); formData.append (' version', versionInfo); formData.append ('strategy', strategyInfo); / / upload file upload.uploadFile (formData)})

Fourth, server interface

1.springboot default implementation

Pom.xml

4.0.0 com.demo demo 0.0.1-SNAPSHOT org.springframework.boot spring-boot-starter-parent 1.5.10.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-devtools true org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf Net.sourceforge.nekohtml nekohtml org.springframework.boot spring-boot-starter-test test io.springfox springfox-swagger2 2.7.0 io.springfox springfox-swagger-ui 2.7.0 org.springframework.boot spring-boot-maven-plugin

Application.yml

Server: port: 8080 tomcat: uri-encoding: UTF-8 application: name: demo thymeleaf: encoding: UTF-8 cache: true mode: LEGACYHTML5 devtools: restart: enabled: true http: multipart: maxFileSize: 500Mb maxRequestSize: 500Mb location: D:/tmpdebug: false

Interface:

@ PostMapping ("/ upload") public String uploadFile (@ RequestParam ("file") MultipartFile file) {if (file = = null | | file.isEmpty ()) {return "file is empty";} / / get the file name String fileName = file.getOriginalFilename (); / / File storage path String filePath = "D:/data/" + UUID.randomUUID (). ToString (). ReplaceAll ("-", ") +" _ "+ fileName; logger.info (" save file to: "+ filePath) File dest = new File (filePath); if (! dest.getParentFile (). Exists ()) {dest.getParentFile (). Mkdirs ();} try {file.transferTo (dest); return "success";} catch (Exception e) {e.printStackTrace ();} return "fail";}

Startup class

Import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.builder.SpringApplicationBuilder;import org.springframework.boot.web.support.SpringBootServletInitializer;import org.springframework.transaction.annotation.EnableTransactionManagement;@SpringBootApplication@EnableTransactionManagementpublic class Application extends SpringBootServletInitializer {@ Override protected SpringApplicationBuilder configure (SpringApplicationBuilder application) {return application.sources (Application.class);} public static void main (String [] args) {SpringApplication.run (Application.class, args);}}

two。 Upload components using commons-fileupload

Application.yml

Server: port: 8080 tomcat: uri-encoding: UTF-8spring: application: name: svc-demo thymeleaf: encoding: UTF-8 cache: false mode: LEGACYHTML5debug: false

Pom .xml

Org.springframework.boot spring-boot-starter-parent 1.5.10.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-devtools true org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-test test commons-io commons-io 2.4 commons-fileupload commons-fileupload 1.3.1 net.sourceforge.nekohtml nekohtml org.springframework.boot spring-boot-maven-plugin

Process class

Public class Progress {private long bytesRead; / / the total number of bits read in the private long contentLength;// file public long getBytesRead () {return bytesRead;} public void setBytesRead (long bytesRead) {this.bytesRead = bytesRead;} public long getContentLength () {return contentLength;} public void setContentLength (long contentLength) {this.contentLength = contentLength;} public long getItems () {return items;} public void setItems (long items)\ {this.items = items }}

Monitoring class

@ Componentpublic class FileUploadProgressListener implements ProgressListener {private HttpSession session; public void setSession (HttpSession session) {this.session=session; Progress status = new Progress (); / / Save upload status session.setAttribute ("status", status);} @ Override public void update (long bytesRead, long contentLength, int items) {Progress status = (Progress) session.getAttribute ("status"); status.setBytesRead (bytesRead); status.setContentLength (contentLength); status.setItems (items);}}

File upload processing class

Public class CustomMultipartResolver extends CommonsMultipartResolver {/ / inject FileUploadProgressListener @ Autowired private FileUploadProgressListener progressListener; public void setFileUploadProgressListener (FileUploadProgressListener progressListener) {this.progressListener = progressListener;} @ Override public MultipartParsingResult parseRequest (HttpServletRequest request) throws MultipartException {String encoding = determineEncoding (request); FileUpload fileUpload = prepareFileUpload (encoding); / / fileUpload.setFileSizeMax (1024 * 1024 * 500); / / maximum 500m / / fileUpload.setSizeMax for a single file (1024 * 1024 * 500) / / submit a maximum of 500m progressListener.setSession (request.getSession ()) of the total file at a time; / / ask the file upload progress listener to set session to store the upload progress fileUpload.setProgressListener (progressListener); / / add the file upload progress listener to fileUpload try {List fileItems = ((ServletFileUpload) fileUpload) .parseRequest (request); return parseFileItems (fileItems, encoding);} catch (FileUploadBase.SizeLimitExceededException ex) {throw new MaxUploadSizeExceededException (fileUpload.getSizeMax (), ex) } catch (FileUploadException ex) {throw new MultipartException ("Could not parse multipart servlet request", ex);}

Controller

@ RestControllerpublic class FileController {@ PostMapping ("/ upload") public String uploadFile (@ RequestParam ("file") MultipartFile file) {if (file.isEmpty ()) {return "file is empty";} / / get file name String fileName = file.getOriginalFilename (); / / path after file upload / / path after file upload String filePath = null; try {filePath = new File ("). GetCanonicalPath () +" / tmp/uploadFile/ " } catch (IOException e) {e.printStackTrace ();} / / Storage path String tagFilePath = filePath + CommonUtil.getCurrentTime () + fileName; File dest = new File (tagFilePath); / / detect whether there is a directory if (! dest.getParentFile (). Exists ()) {dest.getParentFile (). Mkdirs ();} try {file.transferTo (dest);} catch (IllegalStateException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();} return fileName + "upload failed" }}

Startup class

/ / be careful to cancel the automatic Multipart configuration, otherwise you may not get the value of file @ EnableAutoConfiguration (exclude = {MultipartAutoConfiguration.class}) @ SpringBootApplicationpublic class Application extends SpringBootServletInitializer {/ / inject the custom file upload processing class @ Bean (name = "multipartResolver") public MultipartResolver multipartResolver () {CustomMultipartResolver customMultipartResolver = new CustomMultipartResolver (); return customMultipartResolver;} @ Override protected SpringApplicationBuilder configure (SpringApplicationBuilder application) {return application.sources (Application.class) } public static void main (String [] args) {SpringApplication.run (Application.class, args);}

This is the end of this article on "how to achieve the upload function of springboot with progress bar". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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