今天给大家介绍一个常用的jQuery表单插件,jquery.form.js插件,在异步上传文件和下载文件时候非常有用哦,喜欢的朋友可以参考学习下,下面直接进入主题。
1、编写一个简单的前端页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jquery.form表单异步上传和下载文件</title> <script src="jquery.form.min.js"></script> <script> $("#f1").ajaxSubmit({ url: "/api/v1/uploadfile",//访问服务地址 type: "post", //请求方法, enctype: "multipart/form-data", dataType: "json", success: function (response) { try { var data = JSON.parse(response); if (data.code > 0) { console.log("todo something..."); } else { console.log("todo something..."); } } catch (err) { console.log(err); } }, error: function (XmlHttpRequest, textStatus, errorThrown) { console.log("失败的时候做什么处理。。。"); } }); </script> </head> <body> <form id="f1" method="post"> <span class="btn-upload form-group"> <input type="file" multiple name="file-1" class="input-file" > <input type="submit" value="提交"> </span> </form> </body> </html>
简单效果
2.编写后端接口服务
可以简单的写一个servlet服务类,
public class UploadFileServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //接受文件参数 System.out.println("上传的文件进行处理操作"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
注意:前端的ajaxSubmit参数type值,当上传文件时此处的方法配置会被form表单的method覆盖,切记form的method值为post才能和后端服务post方法对接上,通过这种方式上传的文件,前端可以异步进行操作,而不用刷新整个页面,相当于模拟了ajax请求,后续会讲解ajax上传文件的文章。
到这里就结束了,大家可以试试,很简单哦
本文暂时没有评论,来添加一个吧(●'◡'●)