js drag picture / input upload + form submission + ajax upload to struts

Keywords: Attribute Struts JSON github

Effect demonstration:

1. html section

<div class="input_part" type="text">
    <div class="icon_search"></div>
    <input type="text" name="input_text" id="input_text">
    <button id="search_btn">search</button>
    <div class="openImg"></div>
</div>
<div class="image_part js_hide">
    <div class="drag_image" id="drag_image">Drag the picture here</div>
    <div class="button_image">
        <form id="localUploadForm">
            <a><input type="file" name="file" id="localUpload">Upload pictures locally</a>
        </form>
    </div>
    <div class="image_close icono-cross"></div>
</div>

input_part is the search column, and image_part is the drag + upload column. Click on the camera button (openImg) in the search bar to remove js_hide from image_part before displaying the uploaded picture bar. (Imitate Baidu Search)

2. CSS

Too much is not written entirely. One lesson is that when components are not placed in the desired location, try position (absolute or relative), display (inline-block), left, right, margin and other settings.

Highlight the button css for "upload pictures locally".

.button_image{
    position: relative;
    display: inline-block;
    margin: 15px auto;
    height: 50px;
    width: 90%;
}
.button_image a{
    position: absolute;
    display: inline-block;
    background: #fff;
    border: 1px solid #999;
    border-radius: 4px;
    padding: 4px;
    overflow: hidden;
    color: #555;
    text-decoration: none;
    text-indent: 0;
    line-height: 40px;
    width: 100px;
    height: 40px;
    font-size: 14px;
    text-align: center;
    word-break : keep-all;
    left: 0; 
    right: 0; 
    margin: auto;
}
.button_image a:hover{
    border-color: #ea150b;
    cursor: pointer;
    text-decoration: none;
}
#localUpload{
    position: absolute;
    font-size: 20px;
    width:100px;
    height: 50px;
    top: 0px;
    opacity: 0;
}
#localUpload:hover{
    cursor: pointer;
}

3, part js

jquery is only used here.
The process settings are: drag and drop the picture or open the file selector to select the picture. When this operation is completed, the picture is uploaded, and the uploaded image is displayed with the returned result after the return value is obtained.

$(function() {
    clickEvents();
});

function clickEvents(){
    $('.openImg').bind('click',function(event) {
        $(".image_part").removeClass("js_hide");
    });
    $('.image_close').bind('click',function(event) {
        $(".image_part").addClass("js_hide");
    });
    //Click the button to upload
    $(".button_image a").on("change","input[type='file']",function() {
    //The incoming file is this.files[0]
        uploadImage(this.files[0]);
    });
    //Drag and drop uploads
    new dragUpload({
        dragBox : '#drag_image'
    });
}
//Refer to github's two open source articles. See the link at the end of the article for details.
function dragUpload(obj){
    var $dragBox    = $(obj.dragBox),//jQuery object
        JdragBox    = $dragBox[0];//Native object

    //Prevent default rows from browsers. 
    $(document).on({ 
        dragleave:function(e){//Towing away 
            e.preventDefault(); 
        }, 
        drop:function(e){//Drag and drop 
            e.preventDefault(); 
        }, 
        dragenter:function(e){//Drag in 
            e.preventDefault(); 
        }, 
        dragover:function(e){//Dragging and dragging 
            e.preventDefault(); 
        } 
    });

    var dropper = document.getElementById("drag_image");
    dropper.ondragenter = function (e) {
        $(".drag_image").css('background', "#ddd");
        e.preventDefault();
    };
    dropper.ondragover = function (e) {
        e.preventDefault();
    };
    dropper.ondragleave = function (e) {
        $(".drag_image").css('background', "#eee");
        e.preventDefault();
    };

    //Carried target release
    JdragBox.addEventListener('drop',function(e){
        var fileList = e.dataTransfer.files;//Get the file object
        //If there is no file, end the method directly
        if( fileList.length <= 0 ){
            return fasle;
        }else{
            uploadImage(fileList[0]);
            //This article sets up to upload only one file at a time, so no matter how many files are opened, only take the first one.
            //If you want to drag and drop multiple files, it can be recycled. See the link for details.
        }
    },false);
}

//General uploading method of dragging and clicking buttons
function uploadImage(fileObj){
    var obj = fileObj,
    fileType = fileObj.type,
    fileSize = fileObj.size,
    reader = new FileReader();

    var maxSize = 20480;//The maximum size of the uploaded image, unit kb, is 20M in this conversion.
    var reg =  /(image)/;//Rules for judging file types
    //Type of inspection
    if( !reg.test( fileType ) ){
        alert('Not the right data type');
        return false;
    }

    if( fileSize > maxSize*1024 ){
        alert('More material than'+ maxSize +'KB');
        return false;
    }
    //form!!! Put obj in!!!
    var form = new FormData();
    form.append("file", obj);

    $.ajax({
        type : "post",
        url : "act_GetImage",//action in my struts
        data : form,
        processData : false,
        contentType : false,
        success : function(data) {
            //... Here's what the next blog says
            //The main thing is to get the return value (picture link) and display it.
            }
        },
        error : function(data) {
            alert("Submission failed!");
        }
    });
}

4. struts section

All in all, so many LIBS have been used in this project, I can't tell which ones are used by this function and which ones are used by other functions.

Strts. XML wildcard, Baidu.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<constant name="struts.multipart.maxSize" value="20971520" />
    <package name="thisKnowledge" extends="struts-default,json-default">
        <action name="*_*" class="meiko.server.{2}"
            method="{1}_{2}">
            <result name="success" type="json">
                <param name="root">actJson</param>
            </result>
        </action>
    </package>
</struts>

The content about struts should have been blogged before, and the structure is similar.

package meiko.server;

import java.io.File;
import java.io.IOException;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;

public class GetImage extends ActionSupport {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private File file;//This file is the uploaded file. I guess it's because the file tag is used in the form data.
    private String fileContentType;//Then these two values can be obtained without artificial settings, which is very confusing.
    private String fileFileName;

    private JSONArray actJson;

    public String act_GetImage() throws Exception {
        try {
            String target = ("./upload/" + fileFileName);
            File targetFile = new File(target);
            //With this amazing copy file, you can place the file in the specified location.
            FileUtils.copyFile(file, targetFile);

            // This should call an external method or interface to process the image and return the retrieval results.
            // Because it's just a demo, you can write the return value by hand.
            actJson = new JSONArray();
            for(int i = 0;i<8;i++){
                JSONObject json = new JSONObject();
                json.put("path", "../imgs/0"+(i+1)+".jpg");
                json.put("title", (i+1)+".jpg");
                json.put("message", "this is message");
                actJson.add(json);
            }
            return SUCCESS;
        } catch (IOException e) {
            e.printStackTrace();
            return ERROR;
        }
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public JSONArray getActJson() {
        return actJson;
    }

    public void setActJson(JSONArray actJson) {
        this.actJson = actJson;
    }
}

Hmm.................. After writing, I found that there was no < form > tag. Maybe the < form > tag in html can be deleted.

Reference resources:
https://github.com/awarriorer/H5DragImgUpload
https://github.com/zouyang1230/H5-base64-encoder
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects
https://stackoverflow.com/questions/15201071/how-to-get-full-path-of-selected-file-on-change-of-input-type-file-using-jav

Posted by huntrguy102 on Mon, 11 Feb 2019 14:57:18 -0800