web and upload large files over HTTP server to achieve

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. by sending a request to the backend form form

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

            <div class="bbxx wrap">

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

                <inputtype="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

    this.post_file = function ()

    {

        $.each(this.ui.btn, function (i, n) { n.hide();});

        this.ui.btn.stop.show();

        this.State = this.Config.state.Posting;//

        this.app.postFile({ id: this.fileSvr.id, pathLoc: this.fileSvr.pathLoc, pathSvr:this.fileSvr.pathSvr,lenSvr: this.fileSvr.lenSvr, fields: this.fields });

    };

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

2. Send a request to the backend via ajax

            $.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 divided into two parts, part of the initialization, the file upload request notification before the server initialization operation performed by AJAX

    this.md5_complete = function (json)

    {

        this.fileSvr.md5 = json.md5;

        this.ui.msg.text ( "MD5 calculation is completed, connecting to the server ...");

        this.event.md5Complete(this, json.md5);//biz event

 

        var loc_path = encodeURIComponent(this.fileSvr.pathLoc);

        var loc_len = this.fileSvr.lenLoc;

        var loc_size = this.fileSvr.sizeLoc;

        var param = jQuery.extend({}, this.fields, this.Config.bizData, { md5: json.md5, id: this.fileSvr.id, lenLoc: loc_len, sizeLoc: loc_size, pathLoc: loc_path, time: new Date().getTime() });

 

        $.ajax({

            type: "GET"

            , dataType: 'jsonp'

            , Jsonp: "callback" // callback function name from jsonp defined, default random function names are automatically generated for jQuery

            , url: this.Config["UrlCreate"]

            , data: param

            , success: function (sv)

            {

                _this.svr_create(sv);

            }

            , error: function (req, txt, err)

            {

                _this.Manager.RemoveQueuePost(_this.fileSvr.id);

                alert ( "! MD5 message sent to the server error" + req.responseText);

                _this.ui.msg.text ( "MD5 send information to the server error");

                _this.ui.btn.cancel.show();

                _this.ui.btn.stop.hide();

            }

            , complete: function (req, sta) { req = null; }

        });

    };

 

Notification is sent to the server after the file upload

    this.post_complete = function (json)

    {

        this.fileSvr.perSvr = "100%";

        this.fileSvr.complete = true;

        $.each(this.ui.btn, function (i, n)

        {

            n.hide();

        });

        this.ui.process.css("width", "100%");

        this.ui.percent.text("(100%)");

        this.ui.msg.text ( "upload complete");

        this.Manager.arrFilesComplete.push(this);

        this.State = this.Config.state.Complete;

        // delete from the upload list

        this.Manager.RemoveQueuePost(this.fileSvr.id);

        // delete the list never upload

        this.Manager.RemoveQueueWait(this.fileSvr.id);

 

        var param = { md5: this.fileSvr.md5, uid: this.uid, id: this.fileSvr.id, time: new Date().getTime() };

 

        $.ajax({

            type: "GET"

              , dataType: 'jsonp'

              , Jsonp: "callback" // callback function name from jsonp defined, default random function names are automatically generated for jQuery

              , url: _this.Config["UrlComplete"]

              , data: param

              , success: function (msg)

              {

                  _this.event.fileComplete (_this); // trigger event

                  _this.post_next();

              }

              , Error: function (req, txt, err) {alert ( "File - Complete message transmitted to the server Error!" + Req.responseText);}

              , complete: function (req, sta) { req = null; }

        });

    };

 

It should be MD5 a second transmission processing logic, and when the presence of the same file server, the user does not need to re-upload, but pass directly notify the user seconds

    this.post_complete_quick = function ()

    {

        this.fileSvr.perSvr = "100%";

        this.fileSvr.complete = true;

        this.ui.btn.stop.hide();

        this.ui.process.css("width", "100%");

        this.ui.percent.text("(100%)");

        this.ui.msg.text ( "the presence of the same file server, quickly upload successfully.");

        this.Manager.arrFilesComplete.push(this);

        this.State = this.Config.state.Complete;

        // delete from the upload list

        this.Manager.RemoveQueuePost(this.fileSvr.id);

        // delete the list never upload

        this.Manager.RemoveQueueWait(this.fileSvr.id);

        // add to the file list

        this.post_next();

        this.event.fileComplete (this); // trigger event

    };

Here you can see the logical second pass is very simple, not particularly complex.

            There formdat to form = new ();

            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 part

Logical file initialization, the main code is as follows

FileInf fileSvr= new FileInf();

fileSvr.id = id;

fileSvr.fdChild = false;

fileSvr.uid = Integer.parseInt(uid);

fileSvr.nameLoc = PathTool.getName(pathLoc);

fileSvr.pathLoc = pathLoc;

fileSvr.lenLoc = Long.parseLong(lenLoc);

fileSvr.sizeLoc = sizeLoc;

fileSvr.deleted = false;

fileSvr.md5 = md5;

fileSvr.nameSvr = fileSvr.nameLoc;

 

// all the individual files are uuid / file stored

PathBuilderUuid pb = new PathBuilderUuid();

fileSvr.pathSvr = pb.genFile(fileSvr.uid,fileSvr);

fileSvr.pathSvr = fileSvr.pathSvr.replace("\\","/");

 

DBConfig cfg = new DBConfig();

DBFile db = cfg.db();

FileInf fileExist = new FileInf();

    

boolean exist = db.exist_file(md5,fileExist);

// same database file already exists, and there upload progress, the direct use of this information

if(exist && fileExist.lenSvr > 1)

{

     fileSvr.nameSvr = fileExist.nameSvr;

     fileSvr.pathSvr        = fileExist.pathSvr;

     fileSvr.perSvr = fileExist.perSvr;

     fileSvr.lenSvr              = fileExist.lenSvr;

     fileSvr.complete       = fileExist.complete;

     db.Add(fileSvr);

    

     //trigger event

    up6_biz_event.file_create_same(fileSvr);

} // This file does not exist

else

{

     db.Add(fileSvr);

     //trigger event

    up6_biz_event.file_create(fileSvr);

    

     FileBlockWriter fr = new FileBlockWriter();

     fr.CreateFile(fileSvr.pathSvr,fileSvr.lenLoc);

}

Receiving file data blocks, in this logic, we received the file data blocks. Control data were optimized to facilitate debugging. If you can see the data submitted with the controls monitoring tools.

boolean isMultipart = ServletFileUpload.isMultipartContent(request);

FileItemFactory factory = new DiskFileItemFactory();  

ServletFileUpload upload = new ServletFileUpload(factory);

List files = null;

try

{

     files = upload.parseRequest(request);

}

catch (FileUploadException e)

{// parse the file data error 

    out.println("read file data error:" + e.toString());

    return;

  

}

 

FileItem rangeFile = null;

// get all uploaded files

Iterator fileItr = files.iterator();

// loop to process all files

while (fileItr.hasNext())

{

     // get the current file

     rangeFile = (FileItem) fileItr.next();

     if(StringUtils.equals( rangeFile.getFieldName(),"pathSvr"))

     {

         pathSvr = rangeFile.getString();

         pathSvr = PathTool.url_decode(pathSvr);

     }

}

 

boolean verify = false;

String msg = "";

String md5Svr = "";

long blockSizeSvr = rangeFile.getSize();

if(!StringUtils.isBlank(blockMd5))

{

     md5Svr = Md5Tool.fileToMD5(rangeFile.getInputStream());

}

 

verify = Integer.parseInt(blockSize) == blockSizeSvr;

if(!verify)

{

     msg = "block size error sizeSvr:" + blockSizeSvr + "sizeLoc:" + blockSize;

}

 

if(verify && !StringUtils.isBlank(blockMd5))

{

     verify = md5Svr.equals(blockMd5);

     if(!verify) msg = "block md5 error";

}

 

if(verify)

{

     // Save the file block data

     FileBlockWriter res = new FileBlockWriter();

     // create only the first one

     if( Integer.parseInt(blockIndex)==1) res.CreateFile(pathSvr,Long.parseLong(lenLoc));

     res.write( Long.parseLong(blockOffset),pathSvr,rangeFile);

     up6_biz_event.file_post_block(id,Integer.parseInt(blockIndex));

    

     JSONObject o = new JSONObject();

     o.put("msg", "ok");

     o.put("md5", md5Svr); 

     o.put ( "offset", blockOffset); // offset position based on the file block

     msg = o.toString();

}

rangeFile.delete();

out.write(msg);

 

Note:

1. The upper portion of the java code can be used directly, write only need to upload the image path and to collect the data and database can be

2. Use the above upload files to a byte stream, in fact, can also use other streams, the need to improve the reader's own test below

3. BeanUtils is a tool to facilitate the attributes assigned to an entity corresponding to the entity

4. upload files can not be used request.getParameter ( "") acquisition parameters, but rather directly to the parse request, by determining whether or not each file is a file, and then perform corresponding operations (stream file is then read, non-file, temporarily saved to a map.)

Most of the back-end code logic is the same, currently supports MySQL, Oracle, SQL. Before using the need to configure the database, you can refer me to write this article: 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 / welcome into the group to discuss "374992201 "

 

Guess you like

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