• 自定义前端文件上传


    展示部分

    1 <form style="display:none;" id="form-upload" method="post" enctype="multipart/form-data" action="/test/upload">
    2     <input type="hidden"  name="id" value="123">
    3     <input type="file" name="file">
    4 </form>
    5 <button class="btn-upload" id="btn-upload" >上传</button>

    js事件绑定

     1 <script type="text/javascript">
     2 (function(){
     3     // 劫持上传按钮点击事件,以做到文件上传自定义的目的
     4     var objBtnFileUpload = $("#form-upload").find("input[type='file']");
     5     $("btn-upload").click(function(){
     6         objBtnFileUpload.trigger("click");
     7     });
     8     // 文件上传完成,input[type='file']改变,触发上传
     9     objBtnFileUpload.change(function() {
    10             var self = $(this);
    11             var form = self.parent("form");
    12             var formData = new FormData(form[0]);//用这种方式获取值可以不触发页面跳转
    13             $.ajax({
    14                 type : form.attr('method'),
    15                 url : form.attr('action'),
    16                 data : formData,
    17                 mimeType : form.attr('enctype'),
    18                 contentType : false,
    19                 cache : false,
    20                 processData : false
    21             }).success(function(ret) {
    22                 console.log(ret);
    23                 alert("上传成功");
    24             }).fail(function(jqXHR, textStatus, errorThrown) {
    25                 //错误信息
    26                 console.log(jqXHR);
    27                 alert("上传失败!");
    28             });
    29         });
    30     }
    31 })();
    32 </script>

    后台处理

    /**
     * <p>上传后台</p>
     * */
    @RequestMapping(value = "/test/upload", method = RequestMethod.POST)
    @ResponseBody
    public String addFillForm(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        String id = request.getParameter("id");//额外的表单参数可以通过这种方式接收
        byte[] bFile = file.getBytes();
        String strFileName = file.getName();
        //业务逻辑
    
        return "上传成功";
    }
  • 相关阅读:
    Nodejs实现爬虫的几种方式
    你不知道的 Node.js 爬虫原来这么简单
    express 框架
    nodejs简单开发web的demo
    nodejs学习(三)函数
    url模块和underscore模块
    nodejs学习(四)GET/POST请求
    nodejs使用http模块写web的request和 response
    直播预告 | 个推TechDay治数训练营来袭!带你入门数据仓库与维度建模
    个推SDK别名功能使用解析:与第三方账号打通,实现精细化推送
  • 原文地址:https://www.cnblogs.com/chendeming/p/8166368.html
Copyright © 2020-2023  润新知