本文主要是介绍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) {// 多文件转为jsongObjectNames.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);// 得到filenamevar currentFileName = elDel.prev('p').html();// 删除当前的父级lielDel.parent().parent().remove();// 重新赋值数组// 去掉url数组中的当前urlfor(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")@ResponseBodypublic 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);}
}
这篇关于Spring mvc 集成 plupload 上传图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!