Introduction to the use of ajaxFileUpload asynchronous file upload
This article mainly introduces the simple use of ajaxFileUpload to upload files asynchronously. The jQuery plug-in AjaxFileUpload can realize ajax file upload. If you are interested, you can learn more.
Here is a brief introduction to ajaxFileUpload. The jQuery plug-in AjaxFileUpload can realize ajax file upload. Our project uses an architecture that separates jsp and js, so the code is as follows.
First is the jsp part:
<!-- <form method="post"> --> <input type="file" name="n_file" id="fileToUpload" value="上传表格" /> <button id="upload1" class="btn btn-default">上传</button> <!-- </form> -->
Here is why I commented out the form, because there is already another form in my jsp During the debugging process, I found that there might be a conflict and commented out the form. It turns out that ajaxFileUpload can be submitted without a form. Here is the js code part:
$(function(){ //点击打开文件选择器 $("#upload1").on('click', function() { //选择文件之后执行上传 $.ajaxFileUpload({ url:'supplyDataReportUploadExcel', //url自己写 secureuri:false, //这个是啥没啥用 type:'post', fileElementId:'fileToUpload',//file标签的id dataType: 'json',//返回数据的类型 //data:{name:'logan'},//一同上传的数据 success: function (data, status) { // alert(data); // alert(data.msg); // alert(data.success); if(data.success){ alert("upload,success!!!"); window.location.href='supplyDataReport'; }else{ alert(data.msg); window.location.href='supplyDataReport'; } }/*, error: function (data, status, e) { alert(e); }*/ }); }); });
Myself js is not good, I just know how to use this js and cannot completely copy it. It needs to be combined with the actual situation of the project structure, but the comments on what the general parameters are used for are written. Be sure to note that the type of post is consistent with the method=RequestMethod.POST of the Controller method corresponding to the request. Note dataType:'json', be sure to pay attention to the case of json.
ps: Here I want to say that the judgment I use data.success is related to the subsequent entity class AjaxJson. Pay attention! ! ! ! !
By the way, the corresponding js needs to be introduced into the jsp as follows:
<script type="text/javascript">Core.js('./js/iface/upload');</script> <script type="text/javascript" src="libs/jquery/ajaxfileupload.js"></script>
The upload introduced in the first paragraph is the above js Content, our imported js has been encapsulated, so just write it directly. Based on the actual situation, the following js file of the jQuery plug-in AjaxFileUpload will be used.
The next step is how to respond to the Controller method:
@SuppressWarnings("resource") @RequestMapping(value = "/supplyDataReportUploadExcel", method = RequestMethod.POST) public @ResponseBody String supplyDataReportUploadExcel(HttpServletRequest request, HttpServletResponse response,MultipartFile n_file) throws Exception { AjaxJson json = new AjaxJson(); ObjectMapper mapper = new ObjectMapper(); UploadFormBackVo uploadFormBackVo = new UploadFormBackVo(); //判断是否是空的Excel 包括没有标题 if(n_file.getSize()>0){ try{ //先判断 文件名 是否符合规格 因为不知道怎么获取上传文件的路径 后期修改 //获取文件 //验证文件名 String fileName = n_file.getOriginalFilename(); String fileNewName = fileName.replaceAll(".xls", ""); String eL = "[a-zA-Z]+[0-9]{4}-[0-9]{2}-[0-9]{2}"; Pattern p = Pattern.compile(eL); Matcher m = p.matcher(fileNewName); boolean dateFlag = m.matches(); if (!dateFlag) { System.out.println("格式错误"); uploadFormBackVo.setFormName(n_file.getOriginalFilename()); uploadFormBackVo.setUploadTime(new Date()); uploadFormBackVo.setIfsuccess("上传失败,Excel文件名不符合规格!!!"); supplyDataReportService.insert(uploadFormBackVo); json.setSuccess(false); json.setMsg("Excel,NameError!!!"); String jsonStr = mapper.writeValueAsString(json); return jsonStr; } //上传文件 UploadUtil.SaveFileFromInputStream(n_file.getInputStream(), "D:/补数据报表文件", n_file.getOriginalFilename()); InputStream is2 = new FileInputStream("D:/补数据报表文件/"+n_file.getOriginalFilename()); //读取文件进行内容验证 ExcelReader excelReader = new ExcelReader(); Map<Integer, SupplyDataReportBackVo> supplyDataReportBackVos = new HashMap<Integer, SupplyDataReportBackVo>(); String jsonStr = excelReader.readExcelContent(is2,supplyDataReportBackVos,json,n_file); //判断 readExcelContent()解析Excel文件 是否符合规范 如果符合 修改相应数据 if(json.isSuccess()==true){ //遍历map 用value --》SupplyDataReportBackVo 调用 updateById方法 for(SupplyDataReportBackVo supplyDataReportBackVo : supplyDataReportBackVos.values()){ supplyDataReportService.updateById(supplyDataReportBackVo); } System.out.println("获得Excel表格的内容:"); for (int i = 1; i <= supplyDataReportBackVos.size(); i++) { System.out.println(supplyDataReportBackVos.get(i)); } //保存上传记录 uploadFormBackVo.setFormName(n_file.getOriginalFilename()); uploadFormBackVo.setUploadTime(new Date()); uploadFormBackVo.setIfsuccess("上传成功"); supplyDataReportService.insert(uploadFormBackVo); return jsonStr; } // 解析Excel 文件 中 有空值 保存这次上传的记录且删除已上传的Excel文件, 删除已上传的Excel文件已在 readExcelContent()中处理 uploadFormBackVo.setFormName(n_file.getOriginalFilename()); uploadFormBackVo.setUploadTime(new Date()); uploadFormBackVo.setIfsuccess("上传失败,Excel中有空值!!!"); supplyDataReportService.insert(uploadFormBackVo); return jsonStr; } catch (IOException e){ System.out.println(e.getMessage()); } }else{ //ajax返回的数据 json.setSuccess(false); json.setMsg("Upload File Null!!!!!"); String jsonStr = mapper.writeValueAsString(json); return jsonStr; } System.out.println("ajax请求成功"); return ""; / json.setMsg("upload,success!!!"); }
This method only needs to pay attention to a few points, and the rest is the author himself. For its own business logic, the first request method in @RequestMapping is POST, and the second parameter passed in is MultipartFile n_file. This n_file should correspond to the name attribute in the tag in jsp. The third thing to pay attention to is the annotation @ResponseBody on the return value Sting. The remaining two things to pay attention to are AjaxJson and ObjectMapper.
AjaxJson is a model class encapsulated by itself, used to handle ajax. As for ObjectMapper, it is used to convert types. Please use Baidu or brainstorming. The author is also limited to knowing how to use it. Paste AjaxJson below:
package com.zhongxin.web.ops.adrule.model; import java.util.Map; public class AjaxJson { private boolean success = true; private String msg = "ok"; private Object obj = null; private Map<String, Object> attributes; public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getObj() { return obj; } public void setObj(Object obj) { this.obj = obj; } public Map<String, Object> getAttributes() { return attributes; } public void setAttributes(Map<String, Object> attributes) { this.attributes = attributes; } }
The above is the entire content of this article. I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
How to load navigation history when using jQuery mobile class library
Jquery ajax technology implements interval N Pass value to a page in seconds
The above is the detailed content of Introduction to the use of ajaxFileUpload asynchronous file upload. For more information, please follow other related articles on the PHP Chinese website!

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor
