Javaweb uploads files

Part of the JSP that uploads the file

Uploading files can also be done using form requests to the back end, or ajax requests to the back end

1. Send the request to the back end through the form form

         

            

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

                <inputtype=”file” id=”example-file-input” name=”avatar”>

                Save

            

        

The improved code does not require the form tag and is implemented directly by the control. Developers only need to focus on the business logic. JS has already sealed it for us

    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 });

    };

Through the monitoring tool can see the control submitted data, very clear, debugging is also very simple.

2. Send requests to the backend through 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 is divided into two parts. One is initialization. The server is notified of the initialization operation through ajax request before the file is uploaded

    this.md5_complete = function (json)

    {

        this.fileSvr.md5 = json.md5;

This.ui.msg. text(“MD5 calculation completed, start connecting to 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” // Custom jSONp callback function name, default is automatically generated by jQuery random function name

            , 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 (” Error sending MD5 message to server!” + req.responseText);

_this.ui.msg.text(” ERROR sending MD5 message to server “);

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

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

            }

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

        });

    };

Sends notifications to the server after a file is uploaded

    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 completed “);

        this.Manager.arrFilesComplete.push(this);

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

// Delete from upload list

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

// Delete from unuploaded list

        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” // Custom jSONp callback function name, default is automatically generated by jQuery random function name

              , url: _this.Config[“UrlComplete”]

              , data: param

              , success: function (msg)

              {

_this.event.fileComplete(_this); // Trigger the event

                  _this.post_next();

              }

, error: function (req, TXT, err) {alert(” file – send Complete message to server! + req.responseText); }

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

        });

    };

If the same file exists on the server, the user does not need to upload it again. Instead, the user is notified of the second transmission

    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(” Same file exists on server, quick upload succeeded.” );

        this.Manager.arrFilesComplete.push(this);

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

// Delete from upload list

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

// Delete from unuploaded list

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

// Add to the list of files

        this.post_next();

this.event.fileComplete(this); // Trigger the event

    };

Here you can see that the logic of secs is very simple and not particularly complicated.

            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);

                }

            });

The Java part

File initialization logic, 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 single files are stored as uuid/file

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);

// If the same file exists in the database and the upload progress is displayed, this information is directly used

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 the event

    up6_biz_event.file_create_same(fileSvr);

}// This file does not exist

else

{

     db.Add(fileSvr);

// Trigger the event

    up6_biz_event.file_create(fileSvr);

    

     FileBlockWriter fr = new FileBlockWriter();

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

}

Receive file block data. In this logic we receive file block data. Control of the data is optimized for easy debugging. If you use a monitoring tool, you can see the data submitted by the control.

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)

{// Failed to parse file data

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

    return;

  

}

FileItem rangeFile = null;

// Get all uploaded files

Iterator fileItr = files.iterator();

// Loop through 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 file block data

     FileBlockWriter res = new FileBlockWriter();

// Only the first block is created

     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); // Block offset position based on file

     msg = o.toString();

}

rangeFile.delete();

out.write(msg);

Note:

1. The above Java part of the code can be used directly, just need to upload the picture path and collect data and write the data to the database

2. The file uploaded above uses the byte stream, in fact, can also use other streams, this requires readers to improve the test below

  1. BeanUtils is a tool for assigning attributes to entities

Instead of using Request.getParameter (“”) to retrieve parameters, the request will be parsed directly to determine whether each item is a file or a non-file, and then perform operations accordingly.

The back-end code logic is mostly the same and currently supports MySQL,Oracle, and SQL. Need to configure the database before using, can refer to me to write this article: blog.ncmem.com/wordpress/2… Welcome to join the group to discuss “374992201”