springboot项目中利用ajaxfileupload进行图片上传

本文介绍如何在SpringBoot项目中结合ajaxfileupload.js进行图片上传操作。首先,需要引入相关HTML和JS文件,然后覆盖ajaxfileupload.js中的问题代码。在Controller中实现Java上传方法,调用服务层进行实际上传,并设置返回数据的路径配置。最后,通过renderJson()方法将上传结果反馈给前端。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 引入html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/>
	<script src="index.js"></script>
	<script src="ajaxfileupload.js"></script>
	<style>
        .whiteBtn {
            background-color: white;
            color: red;
            border: red 2px solid;
            font-weight: bold;
        }
    </style>
</head>
<body>
	<!--保存活动图片-->
                <div class="col-sm-12" style="background: white; padding:10px 0 10px 0;border-left: 1px darkgray solid;
                                            border-right: 1px darkgray solid;">
                    <h4 style="display: inline-block;float: left; margin: 0 0 0 4%;">PC端&nbsp;&nbsp;图片:</h4>
                    <div class="col-sm-2" style="margin: 0 0 0 2%;padding-left: 5px">
                        <img id="image_1" src="../../images/test.jpg" style="width: 300px;height: 150px">
                        <input type="hidden" style="float:left;margin: 6px 0 0 5px;" id="imgName1" name="imgName"
                               data-type="1">
                    </div>
                    <button type="button" style="border-color: #428bca;color: #428bca"
                            class="btn whiteBtn" id="updateBtn_1" onclick="showUploadDiv(1)">修&nbsp;&nbsp;改
                    </button>
                    <div class="col-sm-2" id="uploadDiv_1" style="display: none;">
                        <form id="form4" enctype="multipart/form-data" class="col-sm-2" style="padding-left: 0px">
                            <input type="file" style="float:left;margin: 6px 0 0 150px;" id="up_1" name="up_name_1"
                                   accept="image/*" onchange="changImg(event,1,1)">
                        </form>
                    </div>
                </div>
                <div class="col-sm-12" style="background: white; padding:10px 0 10px 0; border-bottom: 1px darkgray solid;
                                                     border-left: 1px darkgray solid; border-right: 1px darkgray solid;">
                    <h4 style="display: inline-block;float: left; margin: 0 0 0 4%;">微信端图片:</h4>
                    <div class="col-sm-2" style="margin: 0 0 0 2%;padding-left: 5px">
                        <img id="image_2" src="../../images/test.jpg" style="width: 150px;height: 75px">
                        <input type="hidden" style="float:left;margin: 6px 0 0 5px;" id="imgName2" name="imgName"
                               data-type="2">
                    </div>
                    <button type="button" style="border-color: #428bca;color: #428bca"
                            id="updateBtn_2" class="btn whiteBtn" onclick="showUploadDiv(2)">修&nbsp;&nbsp;改
                    </button>
                    <div class="col-sm-2" id="uploadDiv_2" style="display: none;">
                        <form id="form5" enctype="multipart/form-data" class="col-sm-2" style="padding-left: 0px">
                            <input type="file" style="float:left;margin: 6px 0 0 5px;" id="up_2" name="up_name_2"
                                   accept="image/*" onchange="changImg(event,2,2)">
                        </form>
                    </div>
                </div>
</body>
  • 引入js

/**
 * 显示修改图片的上传div
 */
function showUploadDiv(index) {
    //$("#imageChange_" + index).onclick;
    $("#uploadDiv_" + index).css("display", "block");
}

/**
 * 选择图片显示
 * @param e
 */
function changImg(e, index, type) {
    for (var i = 0; i < e.target.files.length; i++) {
        var file = e.target.files.item(i);
        //验证是否为图片,不是就跳出循环
        if (!(/^image\/.*$/i.test(file.type))) {
            layer.alert("不是图片或者结尾不是png、jpg!")
            continue;
        }
        //实例化FileReader API  
        var freader = new FileReader();
        freader.readAsDataURL(file);
        freader.onload = function (e) {
            $("#image_" + index).attr("src", e.target.result);  //显示图片
        }
        upLoadFile(type);
    }
    $("#uploadDiv_" + index).css("display", "none");
}

/**
 * 图片上传
 * @param type
 * @returns {boolean}
 */
function upLoadFile(type) {
    debugger;
    var animateimg = $("#up_" + type).val(); //获取上传的图片名 带//
    if (animateimg == "" || animateimg == null) {
        layer.alert('上传内容不允许为空');
        return false;
    }
    if (animateimg > 10) {
        layer.alert('上传图片名字过长');
        return false;
    }

    var imgarr = animateimg.split('\\'); //分割
    var myimg = imgarr[imgarr.length - 1]; //去掉 // 获取图片名
    var houzui = myimg.lastIndexOf('.'); //获取 . 出现的位置
    var ext = myimg.substring(houzui, myimg.length).toUpperCase();  //切割 . 获取文件后缀

    var file = $('#up_'+type).get(0).files[0]; //获取上传的文件
    if(type == 1 || type == 2){
        if (ext != '.PNG' && ext != '.JPG') {
            layer.alert('文件类型错误,请上传图片类型');
            return false;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(theFile) {
            var boolean = true;
            var image = new Image();
            image.src = theFile.target.result;
            image.onload = function () {
                if(type==1){
                    if (this.width != 800 || this.height != 400) {
                        layer.alert('活动图片大小为800 x 400');
                        boolean = false;
                    }
                }
                if(type==2){
                    if (this.width != 400 || this.height != 200) {
                        layer.alert('活动图片大小为400 x 200');
                        boolean = false;
                    }
                }

                if(boolean){
                    $.ajaxFileUpload({
                        url: '/PdImgManager/uploadImgManger.do',
                        secureuri: false,//是否用安全提交,默认为false
                        data: {
                            type: type
                        },
                        fileElementId: 'up_' + type,//file选择文件的框的id
                        //  dataType: 'json',//数据返回格式,如果用json,需要修改ajaxfileupload.js中的内容 eval("data = " + data ); -->data = jQuery.parseJSON(jQuery(data).text());
                        async: false,
                        success: function (data) {
                            debugger;
                            if (JSON.parse(data.body.innerHTML).code == 1000) {
                                layer.alert('文件上传成功');
                                var newName = JSON.parse(data.body.innerHTML).newName;
                                $("#imgName" + type).val(newName);
                            } else {
                                layer.alert("上传文件failed");
                            }
                        },
                        error: function (data) {
                            layer.alert("上传文件失败");
                        }
                    });
                }
            }
        }
    }
}


//在ajax中获取对应的参数(ajax请求将路径保存至数据库中)
 //获取页面所有图片
    var verificationType = 1;//0 验证失败 1 验证通过
    var imgList = new Array();
    $("input[name='imgName']").each(function () {
        var imgObj = new Object();
        var imgName = $(this).val();
        var type = $(this).attr("data-type");
        if(type == 1 && imgName == ""){
            layer.alert("活动图片为必传项!");
            verificationType = 0;
            return false;
        }
        if(type == 2 && imgName == ""){
            layer.alert("活动图片为必传项!");
            verificationType = 0;
            return false;
        }
        imgObj.type = type;
        imgObj.imgName = imgName;
        imgList.push(imgObj);
    });
    if(verificationType == 0){
        //结束方法
        return;
    }
  • 引入ajaxfileupload.js(该文件原生的会出现获取参数为null,将以下代码覆盖原文件中代码即可解决)

jQuery.extend({
    handleError: function (s, xhr, status, e) {
        // If a local callback was specified, fire it
        if (s.error) {
            s.error.call(s.context || s, xhr, status, e);
        }

        // Fire the global callback
        if (s.global) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
        }
    },
    createUploadIframe: function (id, uri) {
        //create frame
        var frameId = 'jUploadFrame' + id;

        if (window.ActiveXObject) {
            var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
            if (typeof uri == 'boolean') {
                io.src = 'javascript:false';
            }
            else if (typeof uri == 'string') {
                io.src = uri;
            }
        }
        else {
            var io = document.createElement('iframe');
            io.id = frameId;
            io.name = frameId;
        }
        io.style.position = 'absolute';
        io.style.top = '-1000px';
        io.style.left = '-1000px';

        document.body.appendChild(io);

        return io
    },
    createUploadForm: function (id, fileElementId,data) {
        //create form
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
        var oldElement = $('#' + fileElementId);
        var newElement = $(oldElement).clone();
        $(oldElement).attr('id', fileId);
        $(oldElement).before(newElement);
        $(oldElement).appendTo(form);
        //set attributes
        $(form).css('position', 'absolute');
        $(form).css('top', '-1200px');
        $(form).css('left', '-1200px');
        $(form).appendTo('body');

        if(data){
            for(var i in data){
                $('<input type="hidden" name="'+i+'" value="'+data[i]+'"/>').appendTo(form);
            }
        }
        return form;
    },

    ajaxFileUpload: function (s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = s.fileElementId;
        var form = jQuery.createUploadForm(id, s.fileElementId,s.data);
        var io = jQuery.createUploadIframe(id, s.secureuri);
        var frameId = 'jUploadFrame' + id;
        var formId = 'jUploadForm' + id;
        // Watch for a new set of requests
        if (s.global && !jQuery.active++) {
            jQuery.event.trigger("ajaxStart");
        }
        var requestDone = false;
        // Create the request object
        var xml = {}
        if (s.global)
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function (isTimeout) {
            var io = document.getElementById(frameId);
            try {
                if (io.contentWindow) {
                    xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
                    xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;

                } else if (io.contentDocument) {
                    xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
                    xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
                }
            } catch (e) {
                jQuery.handleError(s, xml, null, e);
            }
            if (xml || isTimeout == "timeout") {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if (status != "error") {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData(xml, s.dataType);
                        // If a local callback was specified, fire it and pass it the data
                        if (s.success)
                            s.success(data, status);

                        // Fire the global callback
                        if (s.global)
                            jQuery.event.trigger("ajaxSuccess", [xml, s]);
                    } else
                        jQuery.handleError(s, xml, status);
                } catch (e) {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if (s.global)
                    jQuery.event.trigger("ajaxComplete", [xml, s]);

                // Handle the global AJAX counter
                if (s.global && !--jQuery.active)
                    jQuery.event.trigger("ajaxStop");

                // Process result
                if (s.complete)
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function () {
                    try {
                        $(io).remove();
                        $(form).remove();

                    } catch (e) {
                        jQuery.handleError(s, xml, null, e);
                    }

                }, 100)

                xml = null

            }
        }
        // Timeout checker
        if (s.timeout > 0) {
            setTimeout(function () {
                // Check to see if the request is still happening
                if (!requestDone) uploadCallback("timeout");
            }, s.timeout);
        }
        try {
            // var io = $('#' + frameId);
            var form = $('#' + formId);
            $(form).attr('action', s.url);
            $(form).attr('method', 'POST');
            $(form).attr('target', frameId);
            if (form.encoding) {
                form.encoding = 'multipart/form-data';
            }
            else {
                form.enctype = 'multipart/form-data';
            }
            $(form).submit();

        } catch (e) {
            jQuery.handleError(s, xml, null, e);
        }
        if (window.attachEvent) {
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else {
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        }
        return {
            abort: function () {
            }
        };

    },

    uploadHttpData: function (r, type) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if (type == "script")
            jQuery.globalEval(data);
        // Get the JavaScript object, if JSON is used.
        if (type == "json")
            data = jQuery.parseJSON(jQuery(data).text());
        // eval( "data = " + data );
        // evaluate scripts within html
        if (type == "html")
            jQuery("<div>").html(data).evalScripts();
        //alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
})
  • controller中加入Java上传方法

           1.其中的pdImgManagerService及productInfoService自行实现;

           2.IMG_PATH属性需要在springboot配置文件中进行配置,即在bootstrap.properties文件中配置

           3.renderJson()方法用来将数据返回前端

//引入要使用的java包

@Controller
@RequestMapping("/一级路径")
public class PdImgManagerController {

    @Autowired
    private PdImgManagerService pdImgManagerService;
	
    @Autowired
    private ProductInfoService productInfoService;
	
    @Value("${IMG_PATH}")
    public String IMG_PATH;  //图片存储路径

    private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	/**
     * 上传图片
     * @param request
     * @param response
     */
    @RequestMapping("/二级路径")
    public void uploadImgManger(HttpServletRequest request, HttpServletResponse response){

        String upFileName=null; //文件存放的全路径
        String clentIp=getIp(request);
        System.out.println("上传图片的客户端IP为:"+clentIp);
        String type = request.getParameter("type");
        Map<String,Object> result = new HashMap<>();
        try {
            MultipartHttpServletRequest mtRequest = (MultipartHttpServletRequest) request;//多部分httpRquest对象    是HttpServletRequest类的一个子类接口   支持文件分段上传对象
            MultipartFile upFile = mtRequest.getFile("up_name_"+type); // 直接获取文件对象
            String targetPath = request.getServletContext().getRealPath("/download")+File.separator; //获取服务器 中file/update 的 url地址
            String targetPath1=IMG_PATH;
            File f = new File(targetPath); //实例硬盘中文件夹(路径)对象
            if(!f.exists()){//判断此路径/文件夹是否存在
                f.mkdirs(); //如果不存在  则创建文件夹/目录
            }
            File f1 = new File(targetPath1); //实例硬盘中文件夹(路径)对象
            if(!f1.exists()){//判断此路径/文件夹是否存在
                f1.mkdirs(); //如果不存在  则创建文件夹/目录
            }
            String originalName = upFile.getOriginalFilename();//获取文件对象原始文件名
            String fileType = originalName.substring(originalName.lastIndexOf(".") + 1, originalName.length());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String tag = sdf.format(new Date());
            String newName=tag + "_" + originalName;

            upFileName = targetPath + newName;// 拼接出文件的要存储的位置(全路径)
            String upFileName1 = targetPath1 + newName;// 拼接出文件的要存储的位置(全路径)
            System.out.println("上传图片路径为:"+targetPath);
            System.out.println("上传图片名称为:"+newName);
            System.out.println("上传图片大小为:"+upFile.getSize());
            System.out.println("上传图片后缀为:"+fileType);
            File file = new File(upFileName);//创建 内存中的File对象
            if(file.exists()){ //判断是否存在
                file.delete();//如果有重名文件存在  就删除文件
            }
            File file1 = new File(upFileName1);//创建 内存中的File对象
            if(file1.exists()){ //判断是否存在
                file1.delete();//如果有重名文件存在  就删除文件
            }
            //upFile.transferTo(file);//转存
            upFile.transferTo(file1);//转存
            result.put("newName",newName);
            result.put("code","1000");

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            renderJson(response,request,JSONObject.fromObject(result).toString());
        }
    }
	
	/**
     * 获取客户端Ip
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");
        String ip = null;
        if (realIp == null) {
            if (forwarded == null) {
                ip = remoteAddr;
            } else {
                ip = remoteAddr + "/" + forwarded;
            }
        } else {
            if (realIp.equals(forwarded)) {
                ip = realIp;
            } else {
                ip = realIp + "/" + forwarded.replaceAll(", " + realIp, "");
            }
        }
        return ip;
    }

    public void renderJson(HttpServletResponse response, HttpServletRequest request, String content) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(content);
            response.getWriter().flush();
        } catch (IOException var4) {
            var4.printStackTrace();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值