Spring mvc 集成 plupload 上传图片

plupload

gObjectName = ''
gObjectNames = new Array() //多图片上传保持
currentUrl = window.location.href;
baseBackend = window.location.protocol + "//" +window.location.host;
uploadUrl = 'http://127.0.0.1:8082/';

$(document).ready(function() {
    //上传
    $('.media-picker').each(function() {
        var el = $(this);
        var elbtn = el.find('.media-picker-button');
        var multiSelection = false;
        // 上传目录
        var inputField = el.find('input[type=hidden]');
        var token = $("meta[name='_csrf']").attr("content");
        var header = $("meta[name='_csrf_header']").attr("content");
        console.log(header)

        // 类型
        var mediaType = elbtn.attr('data-type');
        var mimeTypes = [
            { title: "Image files", extensions: "jpg,jpeg,gif,png,bmp" },
            { title: "Video files", extensions: "mp4,3gp" },
            { title: "Video files", extensions: "pdf,doc,docx,ppt,pptx,xls,xlsx,zip,rar" }
        ];
        if(mediaType == 'video') {
            mimeTypes = [
                { title: "Video files", extensions: "mp4,3gp" }
            ];
        } else if(mediaType == 'file') {
            mimeTypes = [
                { title: "Video files", extensions: "pdf,doc,docx,ppt,pptx,xls,xlsx,zip,rar" }
            ];
        } else if(mediaType == 'image') {
            mimeTypes = [
                { title: "Image files", extensions: "jpg,jpeg,gif,png,bmp" }
            ];
        }

        // 是否多文件上传
        if (elbtn.attr('data-multiple') == 'multiple') {
            multiSelection = true;
            // 如果已经有文件
            var oldFiles = inputField.val();
            if (oldFiles != '') {
                var oldFilesArr = $.parseJSON(oldFiles);
                for (var x = 0; x < oldFilesArr.length; x++) {
                    gObjectNames.push(oldFilesArr[x]);
                }
            }
        }

        var updir = elbtn.attr('data-oss-path');
        var uploader = new plupload.Uploader({
            runtimes: 'html5,flash,silverlight,html4',
            browse_button: elbtn.attr('data-id') + '_uploader',
            url: 'http://127.0.0.1:8082/backend/upload',
            file_data_name: 'file',
            multi_selection: multiSelection,
            auto_start: true,
            flash_swf_url: '../plugins/plupload/js/Moxie.swf',
            silverlight_xap_url: '../plugins/plupload/js/Moxie.xap',

            //只允许上传图片和zip,rar文件

            filters: {
                mime_types: mimeTypes,
                max_file_size: '50mb', //最大只能上传10mb的文件
                prevent_duplicates: false //不允许选取重复文件
            },

            init: {
                PostInit: function() {
                    gObjectNames = new Array() //多图片上传保持
                },
                FilesAdded: function(up) {
                    uploader.setOption("multipart_params", {"updir": updir, "_csrf": token});
                    up.start(); //选择完后直接上传
                },

                FileUploaded: function(up, file, info) {
                    if (info.status == 200) {
                        var fileType = file.type;
                        var isImage = fileType.indexOf('image');
                        var isVideo = fileType.indexOf('video');
                        var isApplication = fileType.indexOf('application');

                        // 获取返回德数据
                        var fileInfos = $.parseJSON(info.response);
                        if(fileInfos.error == 0) {
                            var fileUrl = fileInfos.url;
                            if (multiSelection) {
                                // 多文件转为json
                                gObjectNames.push(fileUrl);
                                inputField.val(JSON.stringify(gObjectNames));

                                var imageHtml = '';
                                for (var i = 0; i < gObjectNames.length; i++) {
                                    if (isImage > -1) {
                                        imageHtml += '<li class="image-info"><div class="info"><img src="' +  gObjectNames[i] + '"/><p>' + gObjectNames[i] + '</p><div class="delete-image"> X </div></div></li>';
                                    }
                                    if (isVideo > -1) {
                                        imageHtml += '<li class="video-info"><div class="info"><video controls src="' +  gObjectNames[i] + '"></video><p>' + gObjectNames[i] + '</p><div class="delete-image"> X </div></div></li>';
                                    }
                                    if (isApplication > -1) {
                                        imageHtml += '<li class="file-info"><div class="info"><div class="attachment-file">' +  gObjectNames[i] + '</div><p>' + gObjectNames[i] + '</p><div class="delete-image"> X </div></div></li>';
                                    }
                                }
                                el.find('.media-list ul').html(imageHtml);

                            } else {
                                // 单文件直接用名称,
                                inputField.val(fileUrl);
                                gObjectName = fileUrl
                                    // 把图片显示出来
                                var imageHtml = '';
                                if (isImage > -1) {
                                    imageHtml = '<li class="image-info"><div class="info"><img src="' +  gObjectName + '"/><p>' + gObjectName + '</p><div class="delete-image"> X </div></div></li>';
                                }
                                if (isVideo > -1) {
                                    imageHtml = '<li class="video-info"><div class="info"><video controls src="' +  gObjectName + '"></video><p>' + gObjectName + '</p><div class="delete-image"> X </div></div></li>';
                                }
                                if (isApplication > -1) {
                                    imageHtml += '<li class="file-info"><div class="info"><div class="attachment-file">' +  gObjectName + '</div><p>' + gObjectName + '</p><div class="delete-image"> X </div></div></li>';
                                }
                                el.find('.media-list ul').html(imageHtml);
                            }
                        } else {
                            alert(fileInfos.msg);
                        }
                    } else {
                        alert(info.response);
                    }
                },

                Error: function(up, err) {
                    if (err.code == -600) {
                        alert("\n选择的文件太大了,可以根据应用情况,在upload.js 设置一下上传的最大大小");
                    } else if (err.code == -601) {
                        alert("\n选择的文件后缀不对,可以根据应用情况,在upload.js进行设置可允许的上传文件类型");
                    } else if (err.code == -602) {
                        alert("\n这个文件已经上传过一遍了");
                    } else {
                        alert("\nError xml:" + err.response);
                    }
                }
            }
        })
        uploader.init();
    })

    // 删除
    $('.media-picker').each(function() {
        var el = $(this)
        var inputField = el.find('input[type=hidden]');
        var fileUrl = inputField.val();
        var elbtn = el.find('.media-picker-button');
        var multiSelection = false;
        // 是否多文件上传
        if (elbtn.attr('data-multiple') == 'multiple') {
            multiSelection = true;
        }
        if (multiSelection) {
            el.on('click', '.delete-image', function() {
                var elDel = $(this);
                // 得到filename
                var currentFileName = elDel.prev('p').html();

                // 删除当前的父级li
                elDel.parent().parent().remove();
                // 重新赋值数组
                // 去掉url数组中的当前url
                for(var i in gObjectNames) {
                    if(gObjectNames[i] == currentFileName) {
                        gObjectNames.splice(i,1);
                       break;
                    }
                }
                // 后端不做删除
                /*$.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                });
                $.ajax({
                    type: "POST",
                    url: baseBackend + "uploader/deluploader",
                    data: "attachement_id=" + currentAttachementId,
                    success: function(msg) {

                    }
                });*/
                inputField.val(JSON.stringify(gObjectNames));
            })
        } else {
            el.on('click', '.delete-image', function() {
                // 显示值为空
                el.find('.media-list ul').html('');
                inputField.val('');

                // oss删除
                if (gObjectName != '') {
                    fileAttachement = gObjectName;
                }
                 // 后端不做删除
                /*$.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                });
                $.ajax({
                    type: "POST",
                    url: baseBackend + "uploader/deluploader",
                    data: "attachement_id=" + fileAttachement,
                    success: function(msg) {

                    }
                });*/
            })
        }

    })
})

 

上传注意时需要注意加入csrf

 

后端

@Controller
@RequestMapping(value = "/backend")
public class UploadController {

    @PostMapping(value = "/upload", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request)
    {
        Map<String, String> jres = new HashMap<String, String>();
        Gson gson = new Gson();

        if(!file.isEmpty()) {
            // 文件夹路径
            // 这里正是环境要处理,spring boot每次重启都会重新生成临时目录
            String uploadPath = request.getSession().getServletContext().getRealPath("upload/");
            String currentDatePath = ToolUtils.makeDatePath();
            String savePath = uploadPath.concat("/").concat(currentDatePath);
            // 获取文件名
            String fileName = file.getOriginalFilename();
            String newFileName = ToolUtils.makeFileName(fileName);

            String showUrl = "/upload/".concat(currentDatePath).concat("/").concat(newFileName);
            File saveFile = new File(savePath, newFileName);
            if (!saveFile.exists()) {
                saveFile.mkdirs();
            }

            try {
                file.transferTo(saveFile);
                jres.put("error", "0");
                jres.put("url", showUrl);
                gson.toJson(jres);
            } catch (Exception e) {
                jres.put("error", "1");
                jres.put("msg", "wrong");
            }
            return gson.toJson(jres);
        }
        jres.put("error", "1");
        jres.put("msg", "wrong");
        return gson.toJson(jres);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值