How to achieve fragmentation webuploader HTTP +

javaweb upload files

jsp file upload in part

Upload file also can use the form form to send the request back-end, you can also send a request to the backend using ajax

    1.  sending a request to form the rear end through the form

         <form id="postForm" action="${pageContext.request.contextPath}/UploadServlet" method="post" enctype="multipart/form-data">

            <div class="bbxx wrap">

                <input type="text" id="side-profile-name" name="username" class="form-control">

                <input type="file" id="example-file-input" name="avatar">

                <button type="submit" class="btn btn-effect-ripple btn-primary">Save</button>

            </div>

        </form>

Improved code labels do not need to form, directly implemented by the control. Developers only need to focus on business logic can be. JS has been closed to help us better

Controls can see the data submitted through the monitoring tool, very clear, very simple debugging.

 

2  sends a request to the backend via ajax

        1.

            $.ajax({ 

                 url : "${pageContext.request.contextPath}/UploadServlet"

                 type : "POST"

                 data : $( '#postForm').serialize(), 

                 success : function(data) { 

                      $( '#serverResponse').html(data); 

                 }, 

                 error : function(data) { 

                      $( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText); 

                 

            }); 

ajax分为两部分,一部分是初始化,文件在上传前通过AJAX请求通知服务端进行初始化操作

 

在文件上传完后向服务器发送通知

 

这里需要处理一个MD5秒传的逻辑,当服务器存在相同文件时,不需要用户再上传,而是直接通知用户秒传

这里可以看到秒传的逻辑是非常 简单的,并不是特别的复杂。

            var form = new FormData();

            form.append("username","zxj");

            form.append("avatar",file);

            //var form = new FormData($("#postForm")[0]);

            $.ajax({

                url:"${pageContext.request.contextPath}/UploadServlet",

                type:"post",

                data:form,

                processData:false,

                contentType:false,

                success:function(data){

         

                    console.log(data);

                }

            });

java部分

文件初始化的逻辑

 

接收文件块数据,在这个逻辑中我们接收文件块数据。控件对数据进行了优化,可以方便调试。如果用监控工具可以看到控件提交的数据。

 

注:

1. 上面的java部分的代码可以直接使用,只需要将上传的图片路径及收集数据并将数据写入到数据库即可

2. 上面上传文件使用到了字节流,其实还可以使用别的流,这个需要读者自己在下面完善测试

3. BeanUtils是一个工具 便于将实体对应的属性赋给实体

4. 上传文件不能使用 request.getParameter("")获取参数了,而是直接将request解析,通过判断每一项是文件还是非文件,然后进行相应的操作(文件的话就是用流来读取,非文件的话,暂时保存到一个map中。)

后端代码逻辑大部分是相同的,目前能够支持MySQL,Oracle,SQL。在使用前需要配置一下数据库,可以参考我写的这篇文章:http://blog.ncmem.com/wordpress/2019/08/12/java-http%E5%A4%A7%E6%96%87%E4%BB%B6%E6%96%AD%E7%82%B9%E7%BB%AD%E4%BC%A0%E4%B8%8A%E4%BC%A0/


Guess you like

Origin www.cnblogs.com/songsu/p/12010473.html