您的位置:首页 > 编程语言 > Java开发

图片 上传 实例 springMVC项目 成功版本

2017-06-29 18:50 274 查看
    本次 图片上传  一波三折     开始引入百度的 webuploader但是 一直没有 调试好   后来 用FormData  提交ajax 也不行      后来引入jquery.form.js     插件   提交表单  终于修成正果

 前台代码如下  role.html

<!DOCTYPE HTML>
<html>
<head>
<!-- head begin -->
<meta charset="utf-8">
<meta name="" content="MStaffInfo_detail.html"/>
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<!--<meta http-equiv="Cache-Control" content="no-siteapp"/>-->
<!--<link rel="Bookmark" href="../logo.ico">-->
<!--<link rel="Shortcut Icon" href="../logo.ico">-->
<!--[if lt IE 9]-->
<script type="text/javascript" src="../lib/html5.js"></script>
<script type="text/javascript" src="../lib/respond.min.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="../static/h-ui/css/H-ui.min.css"/>
<link rel="stylesheet" type="text/css" href="../static/h-ui.admin/css/H-ui.admin.css"/>
<link rel="stylesheet" type="text/css" href="../lib/Hui-iconfont/1.0.7/iconfont.css"/>
<link rel="stylesheet" type="text/css" href="../lib/icheck/icheck.css"/>
<link rel="stylesheet" type="text/css" href="../static/h-ui.admin/skin/default/skin.css" id="skin"/>
<link rel="stylesheet" type="text/css" href="../static/h-ui.admin/css/style.css"/>
<link rel="stylesheet" type="text/css" href="../css/common.css"/>
<link href="../lib/webuploader/0.1.5/webuploader.css" rel="stylesheet" type="text/css">
<link href="../lib/bootstrap-Switch/bootstrapSwitch.css" rel="stylesheet" type="text/css">
<!--<link href="../lib/ueditor/1.4.3/themes/default/css/ueditor.css" rel="stylesheet" type="text/css">-->
<link rel="stylesheet" href="../css/jquery-labelauty.css">
<title></title>
<meta name="keywords" content="">
<meta name="description" content="">
<link rel="stylesheet" type="text/css" href="../lib/layer/2.1/skin/layer.css" id="layui_layer_skinlayercss">
<link rel="stylesheet" type="text/css" href="../lib/My97DatePicker/skin/WdatePicker.css">
<link rel="stylesheet" type="text/css" href="../lib/layer/2.1/skin/layer.ext.css" id="layui_layer_skinlayerextcss">
<link rel="stylesheet" type="text/css" href="../lib/laypage/1.2/skin/laypage.css" id="laypagecss">
</head>
<body id="personal_data">
<div class="pd-10">
<input type="hidden" id="villaId" value="v000001">
<input type="hidden" id="villaNumber" value="1">
<input type="hidden" id="villaType" value="villa">
<!--<div class="pb-10">-->
<!--<h3>人员详情</h3>-->
<!--</div>-->
<div id="content1" class="div_border" style="display: block;">
<div class="text-c div_search">
<!--<form action="" method="post" id="form_personal" class="form form-horizontal">-->
<table class="text-l mt-20"style="margin-bottom: 20px;">
<tr>
<td><span>排序<span class="star pl-5">*</span></span></td>
<td>
<div class="formControls col-sm-12">
<input type="number" id="candidateOrder" name="candidateOrder" class="input-text" min="0" maxlength="3" style="width: 100%"/>
</div>
</td>
</tr>
<tr>
<td><span>姓名<span class="star pl-5">*</span></span></td>
<td>
<div class="formControls col-sm-12">
<input id="name" type="text" name="name" class="input-text">
</div>
</td>
</tr>
<tr>
<td><span>职务<span class="star pl-5">*</span></span></td>
<td>
<div class="formControls col-sm-12">
<input id="resige" type="text" name="name" class="input-text">
</div>
</td>
</tr>
<tr>
<td><span>个人简介</span></td>
<td>
<div class="formControls col-sm-12">
<textarea id="profiles" name="remark"  class="text-l input-text" style="height: 100px;"></textarea>
</div>
</td>
</tr>
<tr>
<td><span>照片<span class="star pl-5"> </span></span></td>
<td style="margin-left: 15px;width: 66%; margin-top: 15px;">
<div class="div_upload_detail_bg">
<ul id="pictureAdd" class="sortable ui-sortable">
</ul>
</div>
<div class="div_upload_detail">
<div class="pt-10 pb-10" style="border: 1px solid #ddd;">
<div class="pl-10 pt-10 pb-10">
<form id="addform" class="form-horizontal" method="post" action="http://wyongan.xicp.net/wdplus-web/uploadApk.do" enctype="multipart/form-data" target="rfFrame">
<div class="div_i_b text-c">
<input type="button" id="submit" class="btn btn-primary radius size-M" value="图片上传">
</div>
<div class="div_i_b text-c">
<input type="file" name="apkFile" id="apkFile" accept="image/png,image/gif,image/jpeg" class="form-control">
</div>
<div class="div_i_b div_upload_detail_text text-r"style="width: 65%">文件必须小于10M。      允许的文件类型: png gif jpg jpeg。</div>
</form>
<iframe id="rfFrame" name="rfFrame" src="about:blank" style="display:none;"></iframe>
</div>
</div>
</div>
</td>
</tr>
</table>
<table class="text-c">
<tr class="text-c">
<button id="save" type="submit" class="btn btn-primary pr-10 radius" style="width: 100px">保存</button>
</tr>
</table>
</div>
</div>

</div>
<script type="text/javascript" src="../lib/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="../lib/icheck/jquery.icheck.min.js"></script>
<script type="text/javascript" src="../lib/jquery.validation/1.14.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="../lib/jquery.validation/1.14.0/validate-methods.js"></script>
<script type="text/javascript" src="../lib/jquery.validation/1.14.0/messages_zh.js"></script>
<script type="text/javascript" src="../lib/layer/2.1/layer.js"></script>
<script type="text/javascript" src="../lib/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="../static/h-ui/js/H-ui.js"></script>
<script type="text/javascript" src="../static/h-ui.admin/js/H-ui.admin.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="../js/md5.min.js"></script>
<script type="text/javascript" src="../js/hmac-sha1.js"></script>
<script type="text/javascript" src="../js/jbase64.js"></script>
<script type="text/javascript" src="../js/jquery.form.js"></script>
<script>
var cache;//局部缓存
var listData;//列表数据
var voteId;
var candidateId;//被投票者Id
var currentState;//投票当前状态
var index = parent.layer.getFrameIndex(window.name);//当前iframe页索引值
//页面刷新加载方法
window.onload = function () {
var url = location.href;
var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
var paraObj = {};
for (i = 0; j = paraString[i]; i++) {
paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
}
voteId = noNull(paraObj.id);
candidateId = (noNull(paraObj.name));
var businessState = noNull(paraObj.state);//详情或新增
currentState = noNull(paraObj.currentstate);
if (businessState == 1) { //详情
queryDetail();
if(currentState == 1 || currentState == 2 ){
$('#save').remove();
}
$('#save').attr("onclick", "updateDetail()");
} else if (businessState == 2) { //新增
$('#save').attr("onclick", "addDetail()");
}
};

//投票候选人新增
function addDetail() {
//        if (checkIfLogin1()==false) return;
var candidateOrder = $('#candidateOrder').val();//排序
var name = $('#name').val();//姓名
var resige = $('#resige').val();//职务
var image = noNull($("#pictureOneAdd1 span img").attr('title'));//图片
var profiles = $('#profiles').val();//个人简历
if(candidateOrder==""){
layer.alert('请填写排序!', {icon: 0}, function(index){
layer.close(index);
$("#candidateOrder").focus();
});
return;
}else if(name==""){
layer.alert('请填写姓名!', {icon: 0}, function(index){
layer.close(index);
$("#name").focus();
});
return;
}else if(resige==""){
layer.alert('请填写职务!', {icon: 0}, function(index){
layer.close(index);
$("#resige").focus();
});
return;
}
var params = {
voteId: voteId,
candidateOrder:candidateOrder,
name:name,
resige:resige,
image:image,
profiles:profiles
};
$.ajax({
type: 'POST',
url: API + addVoteCandidate,
data: JSON.stringify(params),
timeout:timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
},
success: function (result) {
if (result.success == true) {
layer.msg(addSuccess, {icon: 6, time: 1000});
setTimeout(function(){
parent.window.queryballotList();
parent.layer.close(index);
},2000);
parent.window.queryballotList();
} else {
//                    layer.open({title: '温馨提示', content: result.message, icon: 2});
}
},
error: function () {
layer.open({title: '温馨提示', content: serverError, icon: 0});
}
})

}
//详情查询
function queryDetail() {
//        if (checkIfLogin()==false) return;
var params ={
voteId: voteId,
candidateId:candidateId
};
$.ajax({
type: 'POST',
url: API + getVoteCandidateDetails,
data: JSON.stringify(params),
timeout: timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
console.log(JSON.stringify(params))
},
success: function (result) {
if (result.success == true) {
listData = noNull(result.data);//重要参数
tabData();//重要参数tab赋值
//                    layer.msg(querySuccess, {icon: 6, time: 1000});
} else {
layer.open({title: '温馨提示',content: result.message,icon : 2});
}
},
error: function () {
layer.open({title: '温馨提示',content:serverError,icon : 0});
}
})
}
//详情填充数据
function tabData() {
$('#candidateOrder').val(listData.candidateOrder);//排序
$('#name').val(listData.name);//姓名
$('#resige').val(listData.resige);//职务
//        var $str = "";
//        $str += "<span class='maskWraper character_picture_size div_i_b pt-5 pl-5 pr-5' onmousedown='longPressEvent()' onmouseover='floatingLayer()'>";
//        $str += "<img src='"+ API + commentAvatar + noNull(listData.image) + "' title='" + noNull(listData.image) + "' class='character_picture_size'>";
//        $str += "<a class='maskBar text-c ml-5 mr-5' style='text-decoration: none'>" +
//                "<i class='Hui-iconfont' title='删除' onclick='deletePicture($(this))'></i>" +
//                "<i class='Hui-iconfont ml-10' title='原图' onclick='showOriginalPicture($(this))' data-value='"+ API + commentAvatar + listData.image + "'></i>" +
//                "</a>";
//        $str += "</span>";
//        $("#pictureOneAdd1").append($str);//用户头像
$('#profiles').val(listData.profiles);//个人简历
}
//投票候选人修改
function updateDetail() {
//        if (checkIfLogin1()==false) return;
var candidateOrder = $('#candidateOrder').val();//排序
var name = $('#name').val();//姓名
var resige = $('#resige').val();//职务
var image = noNull($("#pictureOneAdd1 span img").attr('title'));//图片
//        var image = "";//照片
//        $("#pictureAdd3 li img").each(function(){image+=$(this).attr('title') + ",";});
var profiles = $('#profiles').val();//个人简历
if(candidateOrder==""){
layer.alert('请填写排序!', {icon: 0}, function(index){
layer.close(index);
$("#candidateOrder").focus();
});
return;
}else if(name==""){
layer.alert('请填写姓名!', {icon: 0}, function(index){
layer.close(index);
$("#name").focus();
});
return;
}else if(resige==""){
layer.alert('请填写职务!', {icon: 0}, function(index){
layer.close(index);
$("#resige").focus();
});
return;
}
var params = {
candidateId: candidateId,
candidateOrder:candidateOrder,
name: name,
resige: resige,
image: '',
profiles: profiles
};
$.ajax({
type: 'POST',
url: API + updateVoteCandidate,
data: JSON.stringify(params),
timeout: timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
console.log(JSON.stringify(params))
},
success: function (result) {
if (result.success == true) {
layer.msg(operationSuccess, {icon: 6, time: 1000});
setTimeout(function () {
parent.window.queryballotList();
parent.layer.close(index);
}, 2000);
parent.window.queryballotList();
} else {
layer.open({title: '温馨提示', content: result.message, icon: 2});
}
},
error: function () {
layer.open({title: '温馨提示', content: serverError, icon: 0});
}
})
}
//图片上传
$("#submit").click(function(){
var options  = {
url: API + uploadApk,   //(服务器地址)同action
type: 'post',
beforeSend:function(xhr){//请求之前
var index = layer.load(1, {
shade: [0.5,'#000'] //0.5透明度的黑色背景
});
},
success:function(data){
layer.closeAll('loading');
console.log("响应数据成功!")
//                var pictureName = data.data.file_name;//图片名
var pictureName = data.file_name;//图片名
if(data.success == true || data.status == "ok"){
var $str = "";
$str += "<li class='maskWraper div_i_b picture_size pt-10 pl-10 mb-10' onmousedown='longPressEvent()' onmouseover='floatingLayer()'>";
$str += "<img src='"+ API + pictureName + "' title='" + pictureName + "' class='picture_size'>";
$str += "<a class='maskBar text-c ml-10'>" +
"<i class='Hui-iconfont' title='删除' onclick='deletePicture($(this))'></i>" +
"<i class='Hui-iconfont ml-10' title='原图' onclick='showOriginalPicture($(this))' data-value='"+ API +  pictureName + "'></i>" +
"</a>";
$str += "</li>";
$("#pictureAdd").append($str);
}
},

complete:function(xhr){//请求完成
layer.closeAll('loading');
},
error: function(xhr,status,msg){
console.log("服务器请求失败!")
layer.msg('玩命加载中..');
}
};
$("#addform").ajaxSubmit(options);
})

</script>
</body>
</html>


引入的 jquery.form.js 插件 如下

/**
* Created by donglian4 on 2017/6/20.
*/
/*!
* jQuery Form Plugin
* version: 3.23 (11-DEC-2012)
* @requires jQuery v1.5 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/ * Project repository: https://github.com/malsup/form * Dual licensed under the MIT and GPL licenses:
*    http://malsup.github.com/mit-license.txt *    http://malsup.github.com/gpl-license-v2.txt */
/*global ActiveXObject alert */
;(function($) {
"use strict";

/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form.  These
functions are mutually exclusive.  Use ajaxSubmit if you want
to bind your own submit handler to the form.  For example,

$(document).ready(function() {
$('#myForm').on('submit', function(e) {
e.preventDefault(); // <-- important
$(this).ajaxSubmit({
target: '#output'
});
});
});

Use ajaxForm when you want the plugin to manage all the event binding
for you.  For example,

$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});

You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
form does not have to exist when you invoke ajaxForm:

$('#myForm').ajaxForm({
delegation: true,
target: '#output'
});

When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/

/**
* Feature detection
*/
var feature = {};
feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
feature.formdata = window.FormData !== undefined;

/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
/*jshint scripturl:true */

// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}

var method, action, url, $form = this;

if (typeof options == 'function') {
options = { success: options };
}

method = this.attr('method');
action = this.attr('action');
url = (typeof action === 'string') ? $.trim(action) : '';
url = url || window.location.href || '';
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/)||[])[1];
}

options = $.extend(true, {
url:  url,
success: $.ajaxSettings.success,
type: method || 'GET',
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options);

// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}

// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}

var traditional = options.traditional;
if ( traditional === undefined ) {
traditional = $.ajaxSettings.traditional;
}

var elements = [];
var qx, a = this.formToArray(options.semantic, elements);
if (options.data) {
options.extraData = options.data;
qx = $.param(options.data, traditional);
}

// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}

// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}

var q = $.param(a, traditional);
if (qx) {
q = ( q ? (q + '&' + qx) : qx );
}
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null;  // data is null for 'get'
}
else {
options.data = q; // data is the query string for 'post'
}

var callbacks = [];
if (options.resetForm) {
callbacks.push(function() { $form.resetForm(); });
}
if (options.clearForm) {
callbacks.push(function() { $form.clearForm(options.includeHidden); });
}

// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
}
else if (options.success) {
callbacks.push(options.success);
}

options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
var context = options.context || this ;    // jQuery 1.4+ supports scope context
for (var i=0, max=callbacks.length; i < max; i++) {
callbacks[i].apply(context, [data, status, xhr || $form, $form]);
}
};

// are there files to upload?

// [value] (issue #113), also see comment:
// https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 var fileInputs = $('input[type=file]:enabled[value!=""]', this);

var hasFileInputs = fileInputs.length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);

var fileAPI = feature.fileapi && feature.formdata;
log("fileAPI :" + fileAPI);
var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;

var jqxhr;

// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, function() {
jqxhr = fileUploadIframe(a);
});
}
else {
jqxhr = fileUploadIframe(a);
}
}
else if ((hasFileInputs || multipart) && fileAPI) {
jqxhr = fileUploadXhr(a);
}
else {
jqxhr = $.ajax(options);
}

$form.removeData('jqxhr').data('jqxhr', jqxhr);

// clear element array
for (var k=0; k < elements.length; k++)
elements[k] = null;

// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;

// utility fn for deep serialization
function deepSerialize(extraData){
var serialized = $.param(extraData).split('&');
var len = serialized.length;
var result = {};
var i, part;
for (i=0; i < len; i++) {
// #252; undo param space replacement
serialized[i] = serialized[i].replace(/\+/g,' ');
part = serialized[i].split('=');
result[decodeURIComponent(part[0])] = decodeURIComponent(part[1]);
}
return result;
}

// XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
function fileUploadXhr(a) {
var formdata = new FormData();

for (var i=0; i < a.length; i++) {
formdata.append(a[i].name, a[i].value);
}

if (options.extraData) {
var serializedData = deepSerialize(options.extraData);
for (var p in serializedData)
if (serializedData.hasOwnProperty(p))
formdata.append(p, serializedData[p]);
}

options.data = null;

var s = $.extend(true, {}, $.ajaxSettings, options, {
contentType: false,
processData: false,
cache: false,
type: method || 'POST'
});

if (options.uploadProgress) {
// workaround because jqXHR does not expose upload property
s.xhr = function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.onprogress = function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
options.uploadProgress(event, position, total, percent);
};
}
return xhr;
};
}

s.data = null;
var beforeSend = s.beforeSend;
s.beforeSend = function(xhr, o) {
o.data = formdata;
if(beforeSend)
beforeSend.call(this, xhr, o);
};
return $.ajax(s);
}

// private function for handling file uploads (hat tip to YAHOO!)
function fileUploadIframe(a) {
var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
var useProp = !!$.fn.prop;
var deferred = $.Deferred();

if ($('[name=submit],[id=submit]', form).length) {
// if there is an input with a name or id of 'submit' then we won't be
// able to invoke the submit fn on the form (at least not x-browser)
alert('Error: Form elements must not have name or id of "submit".');
deferred.reject();
return deferred;
}

if (a) {
// ensure that every serialized input is still enabled
for (i=0; i < elements.length; i++) {
el = $(elements[i]);
if ( useProp )
el.prop('disabled', false);
else
el.removeAttr('disabled');
}
}

s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
id = 'jqFormIO' + (new Date().getTime());
if (s.iframeTarget) {
$io = $(s.iframeTarget);
n = $io.attr('name');
if (!n)
$io.attr('name', id);
else
id = n;
}
else {
$io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
}
io = $io[0];

xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function(status) {
var e = (status === 'timeout' ? 'timeout' : 'aborted');
log('aborting upload... ' + e);
this.aborted = 1;

try { // #214, #257
if (io.contentWindow.document.execCommand) {
io.contentWindow.document.execCommand('Stop');
}
}
catch(ignore) {}

$io.attr('src', s.iframeSrc); // abort op in progress
xhr.error = e;
if (s.error)
s.error.call(s.context, xhr, e, status);
if (g)
$.event.trigger("ajaxError", [xhr, s, e]);
if (s.complete)
s.complete.call(s.context, xhr, e);
}
};

g = s.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && 0 === $.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [xhr, s]);
}

if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
deferred.reject();
return deferred;
}
if (xhr.aborted) {
deferred.reject();
return deferred;
}

// add submitting element to data if we know it
sub = form.clk;
if (sub) {
n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData
= sub.value;
if (sub.type == "image") {
s.extraData[n+'.x'] = form.clk_x;
s.extraData[n+'.y'] = form.clk_y;
}
}
}

var CLIENT_TIMEOUT_ABORT = 1;
var SERVER_ABORT = 2;

function getDoc(frame) {
var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document;
return doc;
}

// Rails CSRF hack (thanks to Yvan Barthelemy)
var csrf_token = $('meta[name=csrf-token]').attr('content');
var csrf_param = $('meta[name=csrf-param]').attr('content');
if (csrf_param && csrf_token) {
s.extraData = s.extraData || {};
s.extraData[csrf_param] = csrf_token;
}

// take a breath so that pending repaints get some cpu time before the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');

// update form attrs in IE friendly way
form.setAttribute('target',id);
if (!method) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}

// ie borks in some cases when setting encoding
if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype:  'multipart/form-data'
});
}

// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
}

// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle)
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
}

// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
if (s.extraData.hasOwnProperty(n)) {
// if using the $.param format that allows for multiple values with the same name
if($.isPlainObject(s.extraData
) && s.extraData
.hasOwnProperty('name') && s.extraData
.hasOwnProperty('value')) {
extraInputs.push(
$('<input type="hidden" name="'+s.extraData
.name+'">').attr('value',s.extraData
.value)
.appendTo(form)[0]);
} else {
extraInputs.push(
$('<input type="hidden" name="'+n+'">').attr('value',s.extraData
)
.appendTo(form)[0]);
}
}
}
}

if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
if (io.attachEvent)
io.attachEvent('onload', cb);
else
io.addEventListener('load', cb, false);
}
setTimeout(checkState,15);
form.submit();
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}

if (s.forceSync) {
doSubmit();
}
else {
setTimeout(doSubmit, 10); // this lets dom updates render
}

var data, doc, domCheckCount = 50, callbackProcessed;

function cb(e) {
if (xhr.aborted || callbackProcessed) {
return;
}
try {
doc = getDoc(io);
}
catch(ex) {
log('cannot access response document: ', ex);
e = SERVER_ABORT;
}
if (e === CLIENT_TIMEOUT_ABORT && xhr) {
xhr.abort('timeout');
deferred.reject(xhr, 'timeout');
return;
}
else if (e == SERVER_ABORT && xhr) {
xhr.abort('server abort');
deferred.reject(xhr, 'error', 'server abort');
return;
}

if (!doc || doc.location.href == s.iframeSrc) {
// response not received yet
if (!timedOut)
return;
}
if (io.detachEvent)
io.detachEvent('onload', cb);
else
io.removeEventListener('load', cb, false);

var status = 'success', errMsg;
try {
if (timedOut) {
throw 'timeout';
}

var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml='+isXml);
if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could be an empty document
//log('Could not access iframe DOM after mutiple tries.');
//throw 'DOMException: not available';
}

//log('response detected');
var docRoot = doc.body ? doc.body : doc.documentElement;
xhr.responseText = docRoot ? docRoot.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (isXml)
s.dataType = 'xml';
xhr.getResponseHeader = function(header){
var headers = {'content-type': s.dataType};
return headers[header];
};
// support for XHR 'status' & 'statusText' emulation :
if (docRoot) {
xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
}

var dt = (s.dataType || '').toLowerCase();
var scr = /(json|script|text)/.test(dt);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
// support for XHR 'status' & 'statusText' emulation :
xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
}
else if (scr) {
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
}
else if (b) {
xhr.responseText = b.textContent ? b.textContent : b.innerText;
}
}
}
else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
xhr.responseXML = toXml(xhr.responseText);
}

try {
data = httpData(xhr, dt, s);
}
catch (e) {
status = 'parsererror';
xhr.error = errMsg = (e || status);
}
}
catch (e) {
log('error caught: ',e);
status = 'error';
xhr.error = errMsg = (e || status);
}

if (xhr.aborted) {
log('upload aborted');
status = null;
}

if (xhr.status) { // we've set xhr.status
status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
}

// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (status === 'success') {
if (s.success)
s.success.call(s.context, data, 'success', xhr);
deferred.resolve(xhr.responseText, 'success', xhr);
if (g)
$.event.trigger("ajaxSuccess", [xhr, s]);
}
else if (status) {
if (errMsg === undefined)
errMsg = xhr.statusText;
if (s.error)
s.error.call(s.context, xhr, status, errMsg);
deferred.reject(xhr, 'error', errMsg);
if (g)
$.event.trigger("ajaxError", [xhr, s, errMsg]);
}

if (g)
$.event.trigger("ajaxComplete", [xhr, s]);

if (g && ! --$.active) {
$.event.trigger("ajaxStop");
}

if (s.complete)
s.complete.call(s.context, xhr, status);

callbackProcessed = true;
if (s.timeout)
clearTimeout(timeoutHandle);

// clean up
setTimeout(function() {
if (!s.iframeTarget)
$io.remove();
xhr.responseXML = null;
}, 100);
}

var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
};
var parseJSON = $.parseJSON || function(s) {
/*jslint evil:true */
return window['eval']('(' + s + ')');
};

var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4

var ct = xhr.getResponseHeader('content-type') || '',
xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
data = xml ? xhr.responseXML : xhr.responseText;

if (xml && data.documentElement.nodeName === 'parsererror') {
if ($.error)
$.error('parsererror');
}
if (s && s.dataFilter) {
data = s.dataFilter(data, type);
}
if (typeof data === 'string') {
if (type === 'json' || !type && ct.indexOf('json') >= 0) {
data = parseJSON(data);
} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
$.globalEval(data);
}
}
return data;
};

return deferred;
}
};

/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
*    is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
*    used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function(options) {
options = options || {};
options.delegation = options.delegation && $.isFunction($.fn.on);

// in jQuery 1.3+ we can fix mistakes with the ready state
if (!options.delegation && this.length === 0) {
var o = { s: this.selector, c: this.context };
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s,o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready?  http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}

if ( options.delegation ) {
$(document)
.off('submit.form-plugin', this.selector, doAjaxSubmit)
.off('click.form-plugin', this.selector, captureSubmittingElement)
.on('submit.form-plugin', this.selector, options, doAjaxSubmit)
.on('click.form-plugin', this.selector, options, captureSubmittingElement);
return this;
}

return this.ajaxFormUnbind()
.bind('submit.form-plugin', options, doAjaxSubmit)
.bind('click.form-plugin', options, captureSubmittingElement);
};

// private event handlers
function doAjaxSubmit(e) {
/*jshint validthis:true */
var options = e.data;
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}

function captureSubmittingElement(e) {
/*jshint validthis:true */
var target = e.target;
var $el = $(target);
if (!($el.is("[type=submit],[type=image]"))) {
// is this a child element of the submit el?  (ex: a span within a button)
var t = $el.closest('[type=submit]');
if (t.length === 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX !== undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') {
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
}

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};

/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property.  An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic, elements) {
var a = [];
if (this.length === 0) {
return a;
}

var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) {
return a;
}

var i,j,n,v,el,max,jmax;
for(i=0, max=els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n) {
continue;
}

if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el) {
a.push({name: n, value: $(el).val(), type: el.type });
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
continue;
}

v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
if (elements)
elements.push(el);
for(j=0, jmax=v.length; j < jmax; j++) {
a.push({name: n, value: v[j]});
}
}
else if (feature.fileapi && el.type == 'file' && !el.disabled) {
if (elements)
elements.push(el);
var files = el.files;
if (files.length) {
for (j=0; j < files.length; j++) {
a.push({name: n, value: files[j], type: el.type});
}
}
else {
// #180
a.push({ name: n, value: '', type: el.type });
}
}
else if (v !== null && typeof v != 'undefined') {
if (elements)
elements.push(el);
a.push({name: n, value: v, type: el.type, required: el.required});
}
}

if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({name: n, value: $input.val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};

/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};

/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++) {
a.push({name: n, value: v[i]});
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({name: this.name, value: v});
}
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};

/**
* Returns the value(s) of the element in the matched set.  For example, consider the following form:
*
*  <form><fieldset>
*      <input name="A" type="text" />
*      <input name="A" type="text" />
*      <input name="B" type="checkbox" value="B1" />
*      <input name="B" type="checkbox" value="B2"/>
*      <input name="C" type="radio" value="C1" />
*      <input name="C" type="radio" value="C2" />
*  </fieldset></form>
*
*  var v = $('input[type=text]').fieldValue();
*  // if no values are entered into the text inputs
*  v == ['','']
*  // if values entered into the text inputs are 'foo' and 'bar'
*  v == ['foo','bar']
*
*  var v = $('input[type=checkbox]').fieldValue();
*  // if neither checkbox is checked
*  v === undefined
*  // if both checkboxes are checked
*  v == ['B1', 'B2']
*
*  var v = $('input[type=radio]').fieldValue();
*  // if neither radio is checked
*  v === undefined
*  // if first radio is checked
*  v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true.  If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array.  If no valid value can be determined the
*    array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
continue;
}
if (v.constructor == Array)
$.merge(val, v);
else
val.push(v);
}
return val;
};

/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}

if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1)) {
return null;
}

if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};

/**
* Clears the form data.  Takes the following actions on the form's input fields:
*  - input text fields will have their 'value' property set to the empty string
*  - select elements will have their 'selectedIndex' property set to -1
*  - checkbox and radio inputs will have their 'checked' property set to false
*  - inputs of type submit, button, reset, and hidden will *not* be effected
*  - button elements will *not* be effected
*/
$.fn.clearForm = function(includeHidden) {
return this.each(function() {
$('input,select,textarea', this).clearFields(includeHidden);
});
};

/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (re.test(t) || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
else if (t == "file") {
if ($.browser.msie) {
$(this).replaceWith($(this).clone());
} else {
$(this).val('');
}
}
else if (includeHidden) {
// includeHidden can be the value true, or it can be a selector string
// indicating a special test; for example:
//  $('#myForm').clearForm('.special:hidden')
// the above would clean hidden inputs that have the class of 'special'
if ( (includeHidden === true && /hidden/.test(t)) ||
(typeof includeHidden == 'string' && $(this).is(includeHidden)) )
this.value = '';
}
});
};

/**
* Resets the form data.  Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};

/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b === undefined) {
b = true;
}
return this.each(function() {
this.disabled = !b;
});
};

/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select === undefined) {
select = true;
}
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
}
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};

// expose debug var
$.fn.ajaxSubmit.debug = false;

// helper fn for console logging
function log() {
if (!$.fn.ajaxSubmit.debug)
return;
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
if (window.console && window.console.log) {
window.console.log(msg);
}
else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}

})(jQuery);


后台 代码如下

package com.weidingplus.mall.web.bg.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.weidingplus.framework.web.entity.JsonResponse;

@Controller
public class UpLoadFileController {

@ResponseBody
@RequestMapping(value = "/uploadApk")
public JsonResponse  uploadApk(@RequestParam(value = "apkFile") MultipartFile apkFile,
HttpServletRequest request, HttpServletResponse response) {
Map<String, String> resMap = new HashMap<String, String>();
// 获取保存的路径,
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "../../upload/";

// 创建文件夹
File file = new File(path);
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}

if (apkFile.isEmpty()) {
// 未选择文件
resMap.put("status", "parm_is_empty");
} else {
// 文件原名称
String originFileName = apkFile.getOriginalFilename();
try {

// 这里使用Apache的FileUtils方法来进行保存
FileUtils.copyInputStreamToFile(apkFile.getInputStream(), new File(path, originFileName));
String newPath = "http://wyongan.xicp.net/wdplus-web/upload" + originFileName;
resMap.put("path", newPath);
resMap.put("status", "ok");
resMap.put("file_name", originFileName);
resMap.put("media_id", "media_id");
} catch (IOException e) {
System.out.println("文件上传失败");
resMap.put("status", "ng");
e.printStackTrace();
}
}
return JsonResponse.getInstanceSuccess(resMap);
}
}


 MultipartFile apkFile需要在springMVC配置当中配置

如下  spring-mvc.xml配置 中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"> 
<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 web -->
<context:component-scan base-package="com.weidingplus.mall.web.*.controller" />

<!--JSP视图解析器-->
<bean id="viewResolverJsp" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/webpage/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
<property name="order" value="1"/>
</bean>

<!-- 配置freeMarker视图解析器 -->
<bean id="viewResolverFtl" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
<property name="contentType" value="text/html; charset=UTF-8"/>
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="cache" value="true" />
<property name="suffix" value=".ftl" />
<property name="order" value="0"/>
</bean>

<!-- 配置freeMarker的模板路径 -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/templates/"/>
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="fmXmlEscape" />
</map>
</property>
<property name="defaultEncoding" value="UTF-8"/>
<property name="freemarkerSettings">
<props>
<!-- 在生产环境下更新模板的间隔要根据实际情况设置,这里为开发方便设置为5秒, 正式环境3600 -->
<prop key="template_update_delay">0</prop>
<prop key="locale">zh_CN</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="number_format">#.##</prop>
</props>
</property>
</bean>

<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 -->
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>

<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!--  <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>  -->
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>

</beans>


spring.xml中 可以忽略

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
">

<!-- 引入DB属性文件 -->
<context:property-placeholder location="classpath:config.properties" />

<!-- 自动扫描(自动注入) web -->
<context:component-scan base-package="com.weidingplus.mall.web.service" />
<context:component-scan base-package="com.weidingplus.mall.web.service.impl" />
<context:component-scan base-package="com.weidingplus.mall.web.mybatis.dao" />
<context:component-scan base-package="com.weidingplus.mall.web.mybatis.pojo" />

<!--============================================国际化相关 start============================================ -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>

<!--============================================获取本地 -->
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
</beans>


另一个可以上传图片的 前台页面

<!DOCTYPE HTML>
<html>
<head>
<!-- head begin -->
<meta charset="utf-8">
<meta name="" content="activity_datail.html" />
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<!--<meta http-equiv="Cache-Control" content="no-siteapp" />-->
<!--<link rel="Bookmark" href="../logo.ico">-->
<!--<link rel="Shortcut Icon" href="../logo.ico">-->
<!--[if lt IE 9]-->
<script type="text/javascript" src="../lib/html5.js"></script>
<script type="text/javascript" src="../lib/respond.min.js"></script>
<!--<script type="text/javascript" src="../lib/PIE_IE678.js"></script>-->
<!--[endif]-->
<link rel="stylesheet" type="text/css" href="../static/h-ui/css/H-ui.min.css" />
<link rel="stylesheet" type="text/css" href="../static/h-ui.admin/css/H-ui.admin.css" />
<link rel="stylesheet" type="text/css" href="../lib/Hui-iconfont/1.0.7/iconfont.css" />
<link rel="stylesheet" type="text/css" href="../lib/icheck/icheck.css" />
<link rel="stylesheet" type="text/css" href="../static/h-ui.admin/skin/default/skin.css" id="skin" />
<link rel="stylesheet" type="text/css" href="../static/h-ui.admin/css/style.css" />
<link rel="stylesheet" type="text/css" href="../css/common.css" />
<link rel="stylesheet" type="text/css" href="../lib/daterangepicker/css/daterangepicker.css" />
<link rel="stylesheet" type="text/css" href="../static/h-ui.admin/css/H-ui.login.css" />
<link rel="stylesheet" type="text/css" href="../lib/bootstrap-Switch/bootstrapSwitch.css">
<!--<link rel="stylesheet" type="text/css" href="../lib/ueditor/1.4.3/themes/default/css/ueditor.css">-->
<link rel="stylesheet" type="text/css" href="../css/jquery-labelauty.css">
<link rel="stylesheet" type="text/css" href="../lib/layer/2.1/skin/layer.css" id="layui_layer_skinlayercss">
<link rel="stylesheet" type="text/css" href="../lib/My97DatePicker/skin/WdatePicker.css">
<link rel="stylesheet" type="text/css" href="../lib/layer/2.1/skin/layer.ext.css" id="layui_layer_skinlayerextcss">
<link rel="stylesheet" type="text/css" href="../lib/laypage/1.2/skin/laypage.css" id="laypagecss">
<link rel="stylesheet" type="text/css" href="../lib/jquery-ui-1.12.1/jquery-ui-1.12.1/jquery-ui.css">
<!--引入wangEditor.css-->
<link rel="stylesheet" type="text/css" href="../lib/wangEditor/2.1.22/dist/css/wangEditor.min.css">
<!--引入取色器.css-->
<!--<link rel="stylesheet" type="text/css" href="../lib/spectrum/spectrum.css">-->
<title>投票管理详情</title>

<style>
.sortable { list-style-type: none; margin: 0; padding: 0; width: 99%; }
.sortable .dropdown:hover{ background: #bdb76b; cursor: move;}
.sortable a{ text-decoration: none;}
.pop{
display: none;
}
.pop:hover{
display: block;
}
.operation:hover+.pop{
display: block;
background-color: #0000FF;
}
</style>

</head>
<body id="villa_content_detail">
<div id="msgDiv"></div>
<div id="bgDiv"></div>
<!-- 面包屑导航架构 -->
<nav class="breadcrumb">
<i class="Hui-iconfont"></i> 首页
<span class="c-gray en">></span>投票管理
<span class="c-gray en">></span> 投票管理列表
<span class="c-gray en">></span> 投票管理详情
<a class="btn btn-success radius r mr-20" style="line-height: 1.6em; margin-top: 3px" href="javascript:location.replace(location.href);" title="刷新"><i class="Hui-iconfont"></i> </a>
</nav>
<div class="pd-10">
<!-- 详情标题 -->
<div class="pb-10">
<h3 id="titleId">投票修改</h3>
</div>
<div id="heig" class="text-c div_i_b div_border div_border_bottom_none" style="height: 30px;">
<div id="tab1" class="div_i_b div_w_h div_r_border div_tab_action" onclick="tab_link(1)"><div class="div_tab_content">基本设置<span class="star pl-5">*</span></div></div>
<div id="tab2" class="div_i_b div_w_h div_r_border " onclick="tab_link(2)"><div class="div_tab_content">问题列表<span class="star pl-5">*</span></div></div>
<div id="tab3" class="div_i_b div_w_h div_r_border" onclick="tab_link(3)"><div class="div_tab_content">被投票者</div></div>
<div id="tab4" class="div_i_b div_w_h" onclick="tab_linkpag()"><div class="div_tab_content">投票预览</div></div>
</div>
<!-- 基本信息 -->
<div id="content1" class="div_border" style="display: block;">
<div class="text-c div_search div_upload mt-20">
<div class="form form-horizontal" id="searchform" style="width: 89.5%">
<table class="text-l">
<tr>
<td style="width:16.4%"><span>投票标题</span><span class="star pl-5">*</span></td>
<td style="width:33.5%">
<input type="text" id="voteTitle" name="voteTitle" class="input-text" placeholder=""/>
</td>
<td style="width:16.4%"></td>
<td style="width:33.5%"></td>
</tr>
<tr>
<td style="width:16.4%"><span>开始日期</span><span class="star pl-5">*</span></td>
<td style="width:33.5%">
<input maxlength="19"  id="startDate" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:dd'})" type="text" class="input-text Wdate" onkeyup="this.value=this.value.replace(/[^0-9-]/g,'')"/>
</td>
<td style="width:16.4%"><span>截止日期</span><span class="star pl-5">*</span></td>
<td style="width:33.5%">
<input maxlength="19" id="endDate" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:dd'})" type="text" class="input-text Wdate" onkeyup="this.value=this.value.replace(/[^0-9-]/g,'')"/>
</td>
</tr>
</table>
<table class="text-l mt-10 mb-10">
<tr>
<td style="width:16.4%;vertical-align: top;"><span>投票图片</span></td>
<td style="width:100%">
<div class="div_upload_detail_bg">
<ul id="pictureAdd" class="sortable ui-sortable">
</ul>
</div>
<div class="div_upload_detail">
<div class="pt-10 pb-10" style="border: 1px solid #ddd;">
<div class="pl-10 pt-10 pb-10">
<form id="addform" class="form-horizontal" method="post" action="http://wyongan.xicp.net/wdplus-web/uploadApk.do" enctype="multipart/form-data" target="rfFrame">
<div class="div_i_b text-c">
<input type="button" id="submit" class="btn btn-primary radius size-M" value="图片上传">
</div>
<div class="div_i_b text-c">
<input type="file" name="apkFile" id="apkFile" accept="image/png,image/gif,image/jpeg" class="form-control">
</div>
<div class="div_i_b div_upload_detail_text text-r">文件必须小于10M。      允许的文件类型: png gif jpg jpeg。</div>
</form>
<iframe id="rfFrame" name="rfFrame" src="about:blank" style="display:none;"></iframe>
</div>
</div>
</div>
</td>
</tr>
</table>
<table class="text-l">
<tr>
<td style="width:16.4%;vertical-align: top;"><span>规则</span><span class="star pl-5">*</span></td>
<td style="width:100%">
<textarea id="rule" name="voteTitle" class="text-l input-text" style="height: 100px"></textarea>
</td>
</tr>
<tr>
<td style="width:16.4%;vertical-align: top;"><span>备注</span></td>
<td style="width:100%">
<textarea id="remarks" name="remarks" class="text-l input-text" style="height: 100px"></textarea>
</td>
</tr>
<tr>
<td style="width:16.4%"><span>投票发送者:</span><span class="star pl-5">*</span></td>
<td style="width:33.5%">
<div></div>
<div class="radio-box">
<input type="radio" value="1"  id="voterList-1" name="voterList">
<label for="voterList-1">全公司</label>
</div>
<div class="radio-box">
<input type="radio" value="2"  id="voterList-2" name="voterList">
<label for="voterList-2">指定对象</label>
</div>
</td>
<td style="width:16.4%"></td>
<td style="width:33.5%">
</td>
</tr>
</table>
<div id="specifiedObject" class="div_i_b text-l w-100 hidden">
<div class="text-l div_upload_left"></div>
<div class="text-l div_border org-div div_upload_right" style="margin-left: -13px;">
<ul class="w-100">

</ul>
<div id="addMember" class="f-r" style="color: #ff9901">
<img onclick="addUser()" src="../img/add.png" class="p10" style="cursor: pointer;width: 30px;height: 30px;">
</div>
</div>
</div>
<table class="text-l mt-20 mb-20">
<tbody id="allCompany">
<tr>
<td style="width:16.4%"></td>
<td style="width:33.5%">
<div class="radio-box">
<input type="checkbox" value="1"  name="showFlag" id="showFlag" >
<label >允许成员查看投票结果</label>
</div>
<td style="width:16.4%"></td>
<td style="width:33.5%">
</td>
</tr>
<tr>
<td style="width:16.4%"></td>
<td style="width:33.5%">
<div class="radio-box">
<input type="checkbox" value="1"  name="anonymousFlag" id="anonymousFlag" checked="checked">
<label>匿名投票</label>
</div>
<td style="width:16.4%"></td>
<td style="width:33.5%">
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- 问题列表 -->
<div id="content2" class="div_border" style="display: none;">
<div class="text-c div_search mt-20" style="width: 100%;padding-left: 0px;">
<table class="text-l">
<tr>
<td style="width: 1%"></td>
<td style="width: 10%">
<a id="deleteQuery" class="btn btn-danger radius size-M form-button" onclick="deteleDetailQuery()">
<i class="Hui-iconfont"></i> 批量删除
</a>
</td>
</td>
<td style="width: 10px"></td>
<td style="width: 10%">
<a id="addBallot" class="btn btn-primary  radius size-M form-button" style="display: none" >
<i class="Hui-iconfont"></i>
新增
</a>
</td>
<td style="width: 10px"></td>
<td style="width: 10%">
<a id="save" class="btn btn-primary  radius size-M form-button" style="display: none" >
<i class="Hui-iconfont"></i>
排序保存
</a>
</td>
<td></td>
</tr>
</table>
<div class="mt-10 margin-style">
<table class="table table-border table-bordered table-bg table-hover table-sort">
<thead>
<tr class="text-c">
<th style="width:5%"><input type="checkbox" id="checkAll" value="" onclick="allSelect($(this),'question')"></th>
<th width="30">排序</th>
<th style="width: 55px">标题</th>
<th width="100">类型</th>
<th width="200">备注</th>
<th width="80">操作</th>
</tr>
</thead>
<tbody id="tbody_data2">
<tr class="text-c"><td style="text-align:center" colspan="6">暂无数据...</td></tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- 被投票者 -->
<div id="content3" class="div_border" style="display: none;">
<div class="text-c div_search mt-20" style="width: 100%;padding-left: 0px;">
<table class="text-l">
<tr>
<td style="width: 1%"></td>
<td style="width: 10%">
<a id="deleteByQuery" class="btn btn-danger radius size-M form-button" onclick="deteleByQuery()">
<i class="Hui-iconfont"></i> 批量删除
</a>
</td>
<td style="width: 10px"></td>
<td style="width: 10%">
<a id="newAdd" class="btn btn-primary  radius size-M form-button" style="display: none" >
<i class="Hui-iconfont"></i>
新增
</a>
</td>
<td style="width: 10px"></td>
<td style="width: 10%">
<a id="save-2" class="btn btn-primary  radius size-M form-button" style="display: none" >
<i class="Hui-iconfont"></i>
排序保存
</a>
</td>
<td></td>
</tr>
</table>
<div class="mt-10 margin-style">
<table class="table table-border table-bordered table-bg table-hover table-sort">
<tbody>
<tr class="text-c" style="background-color: #f5fafe;">
<th style="width:5%"><input type="checkbox" id="checkAll1" value="" onclick="allSelect($(this),'voters')"></th>
<th style="width: 55px">排序</th>
<th width="120">姓名</th>
<th width="100">职务</th>
<th width="100">照片</th>
<th width="200">个人简介</th>
<th width="80">操作</th>
</tr>
</tbody>
<tbody id="tbody_data1">
<tr class="text-c"><td style="text-align:center" colspan="7">暂无数据...</td></tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- 表单底部按钮组 -->
<div class="bg-1 pt-20">
<div class="f-l" style="width: 55%"></div>
<div class="f-r pb-20" style="padding-bottom: 50px;">
<a style="width:125px;" id="save_save" class="btn btn-primary  radius size-M pr-10 " onclick=""><i class="Hui-iconfont"></i> 保存基本信息</a>
<a style="width: 90px;" id="back" class="btn btn-primary radius size-M pr-10 " onclick="back()"><i class="Hui-iconfont"></i> 返回</a>
</div>
</div>
</div>
<input type="hidden" name="addVoteId" id="addVoteId" value=""/>

<script type="text/javascript" src="../lib/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="../js/ajaxfileupload.js"></script>
<script type="text/javascript" src="../js/jquery.form.js"></script>
<script type="text/javascript" src="../lib/jquery-ui-1.12.1/jquery-ui-1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="../lib/layer/2.1/layer.js"></script>
<script type="text/javascript" src="../lib/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="../static/h-ui/js/H-ui.js"></script>
<script type="text/javascript" src="../static/h-ui.admin/js/H-ui.admin.js"></script>
<script type="text/javascript" src="../js/hmac-sha1.js"></script>
<script type="text/javascript" src="../js/jbase64.js"></script>
<script type="text/javascript" src="../js/plupload.full.min.js"></script>
<script type="text/javascript" src="../lib/wangEditor/2.1.22/dist/js/wangEditor.min.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script>
function tab_linkpag() {
window.open (API+'initMVotePreview.do?voteId='+voteId+'&previewFlag=1','newwindow','height=500,width=350,top=100,left=500,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no')
}
$("input[name='voterList']").click(function () {
//为"1"时,选中全公司
if(this.value == "1"){
//$("#allCompany").removeClass("hidden");
$("#specifiedObject").addClass("hidden");
}else if(this.value == "2"){
$("#specifiedObject").removeClass();
//$("#allCompany").addClass("hidden");
}
});

//全选按钮方法
function allSelect(dom,state){
if(state=="question"){
$('#tbody_data2 input[name="checked"]').prop('checked', $(this).prop('checked'));
}else if(state=="voters"){
if(dom[0].checked == true){
$('#tbody_data1 tr input[name="checked"]').prop('checked', 'true');
}else{
$('#tbody_data1 tr input[name="checked"]').prop('checked', '');
}
}
}

//删除用户
function removeUser(dom){
dom.parent().remove();
}

//添加用户弹层
function addUser(){
var meberData = '';//成员或部门ID集合
var departmentData = '';//部门ID集合
var nameData = '';//成员名或部门名集合
var waiverFlagData = '';//区分部门(department)和成员(member)集合
//获取投票发送者成员列表
$("#specifiedObject ul li").each(function(i){
var memberId = noNull($(this)[0].attributes[1].value);//成员ID
var memberName = noNull($(this)[0].attributes[2].value);//成员名
var waiverFlag = noNull($(this)[0].attributes[3].value);//成员或部门状态
var departmentId = noNull($(this)[0].attributes[4].value);//部门ID
meberData += memberId + ',';
departmentData += departmentId + ',';
nameData += memberName + ',';
waiverFlagData += waiverFlag + ',';
});
meberData = meberData.substring(0,meberData.length-1);
departmentData = departmentData.substring(0,departmentData.length-1);
nameData = nameData.substring(0,nameData.length-1);
waiverFlagData = waiverFlagData.substring(0,waiverFlagData.length-1);
layer.open({
type: 2,
title: '<h4><b>添加部门成员</b></h4>',
shadeClose: true,
skin: 'layui-layer-rim', //加上边框
shade:0.4,
area: ['800px', '80%'],
content: 'departmentMember.html?meberData=' + meberData + "&departmentData=" + departmentData + "&nameData=" + nameData + "&waiverFlagData=" + waiverFlagData
});
}
//返回事件
function back(){
history.go(-1);
}

</script>
<script type="text/javascript">
var businessState;//页面状态
var currentState;//投票当前状态
var voteId;//详情Id
var questionsId;//查看投票选项传值
var listData;
var listData2;
var listData3;
var index = parent.layer.getFrameIndex(window.name);//当前iframe页索引值
window.onload = function(){
request();//传递的参数
var voteId = $('#addVoteId').val();
if(businessState==1){//详情
$('#tab1').click(function () {
$('#save').hide();
$('#save_save').show();
});
$('#tab2').click(function () {
if(voteId != ""){
$('#save_save').hide();
}
$('#newAdd').show();
$('#addBallot').show();
$('#save').show();
});
$('#tab3').click(function () {
if(voteId != ""){
$('#save_save').hide();
}
$('#save').show();
$('#newAdd').show();
$('#addBallot').show();
$('#save-2').show();
});
$('#save_save').attr("onclick","updateDetail()");

if(currentState == 1 || currentState == 2 ){
$('li i').attr("onclick",'');
$('#addMember').remove();
$('#deleteQuery').remove();
$('#addBallot').remove();
$('#save').remove();
$('#deleteByQuery').remove();
$('#newAdd').remove();
$('#save-2').remove();
$("#voteTitle").attr("disabled",true);
$("#pictureUpload1").remove();
$("#rule").attr("disabled",true);
$("#remarks").attr("disabled",true);
$("#voterList-1").attr("disabled",true);
$("#voterList-2").attr("disabled",true);
$(".radio-box input").attr("disabled",true);
}

queryDetail();
queryballotList();//投票候选人列表查询
queryList();//投票选项查询
}else if(businessState==2){//新增
$('#tab1').click(function () {
$('#save').hide();
$('#save_save').show()
});
$('#tab2').click(function () {
if(voteId != ""){
$('#save_save').hide();
}
});
$('#tab3').click(function () {
if(voteId != ""){
$('#save_save').hide();
}
});
$('#tab4').click(function () {
if(voteId != ""){
$('#save_save').hide();
}
});
$('#save_save').attr("onclick","addDetail()");
$("#titleId").text("投票新增: " );
}
};
//获取目的地内容传递的参数
function request() {
var url = location.href;
var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
var paraObj = {};
for (i = 0; j = paraString[i]; i++) {
paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
}
voteId = noNull(paraObj.id);
$('#addVoteId').val(voteId);
businessState = noNull(paraObj.state);
currentState = noNull(paraObj.currentstate);

}
$('#newAdd').click(function () {
layer.open({
type: 2,
title: '<h4><b>被投票者</b></h4>',
shadeClose: true,
skin: 'layui-layer-rim', //加上边框
shade:0.4,
area: ['800px', '85%'],
content: 'role.html?id='+voteId+"&state=2"
});
});
$('#addBallot').click(function () {
layer.open({
type: 2,
title: '<h4><b>问题内容</b></h4>',
shadeClose: true,
skin: 'layui-layer-rim', //加上边框
shade:0.4,
area: ['800px', '75%'],
content: 'ballotOption.html?id='+voteId+"&state=2"
});
});
//问题列表排序的保存
$('#save').click(function () {
updateQuestions();
});
//被投票者排序的保存
$('#save-2').click(function () {
updateCandidate();
});

//问题列表排序的保存
function updateQuestions(){
var questionsList = [];//问题集合
$('#tbody_data2 input[name="purchases"]').each(function(i){
var questions = $(this)[0].id;
var questionsOrder =  $(this)[0].value;
questionsList[i]={
questionsId:questions,
questionsOrder:questionsOrder
}
});
if(questionsList==""){
layer.open({title: '温馨提示', content: '暂无数据,不能保存排序!', icon: 2});
return;
}
var params = {
voteId:voteId,
questionsList:questionsList
};
$.ajax({
type: 'POST',
url: API + updateQuestionsOrders,
data: JSON.stringify(params),
timeout:timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
},
success: function (result) {
if (result.success == true) {
layer.msg(operationSuccess, {icon: 6, time: 1000});
setTimeout(function () {
queryList();//投票选项查询
}, 2000);
} else {
layer.open({title: '温馨提示', content: result.message, icon: 2});
//layer.open({title: '温馨提示', content: '暂无数据,不能保存排序!', icon: 2});
}
},
error: function () {
layer.open({title: '温馨提示', content: serverError, icon: 0});
}
})
}

//被投票者排序的保存
function updateCandidate(){
var candidateList = [];//投票候选人ID
$('#tbody_data1 input[name="purchases"]').each(function(i){
var candidate = $(this)[0].id;
var candidateOrder =  $(this)[0].value;
candidateList[i]={
candidateId:candidate,
candidateOrder:candidateOrder
}
});
if(candidateList == ""){
layer.open({title: '温馨提示', content: '暂无数据,不能保存排序!', icon: 2});
return;
}
var params = {
voteId:voteId,
candidateList:candidateList
};
$.ajax({
type: 'POST',
url: API + updateCandidateOrders,
data: JSON.stringify(params),
timeout:timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
},
success: function (result) {
if (result.success == true) {
layer.msg(operationSuccess, {icon: 6, time: 1000});
setTimeout(function () {
queryballotList()
}, 2000);
} else {
layer.open({title: '温馨提示', content: result.message, icon: 2});
}
},
error: function () {
layer.open({title: '温馨提示', content: serverError, icon: 0});
}
})
}

//被投票者页面跳转
function detailPage(dom,state){
var ballotId = "";//取得点击修改后的任务Id。
var name = "";//名字
if(state==1){
ballotId =dom.parent()[0].id;//取得点击修改后的任务Id。
candidateId = $(dom.parent()).attr("name");
}else if(state==2){
ballotId = $(dom.parent().parent().siblings()[2]).attr("id");//取得点击修改后的任务Id。
candidateId = $(dom.parent().parent().siblings()[2]).attr("name");
}
layer.open({
type: 2,
title: '<h4><b>被投票者</b></h4>',
shadeClose: true,
skin: 'layui-layer-rim', //加上边框
shade:0.4,
area: ['800px', '85%'],
content: 'role.html?id=' + ballotId +"&name="+candidateId + "&state=1" + "¤tState=" + currentState
});

}

//投票选项页面跳转
function detailPage2(dom,state){
var voteId = "";//取得点击修改后的任务Id。
var questionsId ="";//投票id
if(state==1){
voteId = $(dom.parent()).attr("id");//取得点击修改后的任务Id。
questionsId = $(dom.parent()).attr("name");
}else if(state==2){
voteId = $(dom.parent().parent().siblings()[2]).attr("id");//取得点击修改后的任务Id。
questionsId = $(dom.parent().parent().siblings()[2]).attr("name");
}
layer.open({
type: 2,
title: '<h4><b>问题内容</b></h4>',
shadeClose: true,
skin: 'layui-layer-rim', //加上边框
shade:0.4,
area: ['800px', '75%'],
content: 'ballotOption.html?id=' + voteId +"&questionsId="+questionsId + "&state=1" + "¤tState=" + currentState
});
}

//详情查询
function queryDetail() {
//        if (checkIfLogin()==false) return;
var params = {
voteId: voteId,
};
$.ajax({
type: 'POST',
url: API + getVoteSetMessage,
data: JSON.stringify(params),
timeout:timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function (result) {
if (result.success == true) {
listData3 = noNull(result.data);//重要参数
tabData();//重要参数tab赋值
if(listData3.state=="未发布"){
$('#endDate').attr('readonly','readonly')
}
//                    layer.msg(querySuccess, {icon: 6, time: 1000});
} else {
layer.open({title: '温馨提示',content: result.message,icon : 2});
}
},
error: function () {
layer.open({title: '温馨提示',content:serverError,icon : 0});
}
})
}

//详情新增
function addDetail(){
//        if (checkIfLogin()==false) return;
var addVoteId = $('#addVoteId').val();//投票标题
var voteTitle = $('#voteTitle').val();//投票标题
var rule = $('#rule').val();//规则
var startDate = $('#startDate').val();//开始投票时间
var endDate = $('#endDate').val();//结束投票时间
var remarks = $('#remarks').val();//备注
var showFlag = $("input[name='showFlag']:checked").val();//是否允许查看投票结果
if(showFlag ==undefined){
showFlag = 0;
}
var anonymousFlag = $("input[name='anonymousFlag']:checked").val();//是否匿名投票
if(anonymousFlag ==undefined){
anonymousFlag = 0;
}
var state ='0';//状态

var companySelectFlag = $("input[name='voterList']:checked").val();//公司
var voterList = [];//投票者
$("#specifiedObject li").each(function(i){
var id = $(this)[0].attributes[1].value;//成员id
var name = $(this)[0].attributes[2].value;//成员名
var waiverFlag = $(this)[0].attributes[3].value;//区分部门(department)和成员(member)
//为部门时(department)则只传部门自己ID
if(waiverFlag == "department"){
voterList[i] = {
wechatDepartmentId: id,
wechatUserName: name
};
//为成员时(member)则成员自己ID和部门自己ID同时上传
}else if(waiverFlag == "member"){
var departmentId = $(this)[0].attributes[4].value;//部门ID(departmentId)
voterList[i] = {
wechatUserId: id,
wechatUserName: name,
wechatDepartmentId: departmentId
}
}
});

// 选择指定部门时,做判断
if(companySelectFlag != "1" && companySelectFlag != "2"){
layer.alert('请投票者发送者!', {icon: 0}, function(index){
layer.close(index);
});
return;
}
if(companySelectFlag == 2){
if(voterList == null || voterList.length == 0){
layer.alert('请投票者发送者!', {icon: 0}, function(index){
layer.close(index);
});
return;
}
}

var image = "";//图片添加
$("#pictureAdd3 li img").each(function(){image+=$(this).attr('title') + ",";});
if(voteTitle==""){
layer.alert('请添写投票标题!', {icon: 0}, function(index){
layer.close(index);
$("#voteTitle").focus();
});
return;
}else if(rule==""){
layer.alert('请添写规则!', {icon: 0}, function(index){
layer.close(index);
$("#rule").focus();
});
return;
}else if(startDate==""){
layer.alert('请添写开始投票时间!', {icon: 0}, function(index){
layer.close(index);
$("#startDate").focus();
});
return;
}else if(endDate==""){
layer.alert('请添写结束投票时间', {icon: 0}, function(index){
layer.close(index);
$("#endDate").focus();
});
return;
}

var params = {
voteId: addVoteId,
voteTitle: voteTitle,
image: image,
rule: rule,
startDate: startDate,
endDate: endDate,
remarks: remarks,
state: state,
companySelectFlag:companySelectFlag,
showFlag:showFlag,
anonymousFlag:anonymousFlag,
voterList:voterList
};
showMyLoading();
console.log(JSON.stringify(params));
$.ajax({
type: 'POST',
url: API + addVote,
data: JSON.stringify(params),
timeout:timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
},
success: function(result){
hideMyLoading();
if(result.success==true){
layer.open({content: '保存成功,请添加其他信息!',icon: 6});
$('#newAdd').show();
$('#addBallot').show();
$('#save').show();
$('#save-2').show();
voteId = result.data.voteId;
$('#addVoteId').val(voteId);
queryballotList();//投票候选人列表查询
queryList();//投票选项查询
}else{
layer.open({title: '温馨提示',content: result.message,icon : 2});
}
},
error: function(){
hideMyLoading();
layer.open({title: '温馨提示',content:serverError,icon : 0});
}
})
}

//基本设置的修改
function updateDetail() {
//        if (checkIfLogin1()==false) return;
var voteTitle = $('#voteTitle').val();//投票标题
var rule = $('#rule').val();//规则
var startDate = $('#startDate').val();//开始投票时间
var endDate = $('#endDate').val();//结束投票时间
var remarks = $('#remarks').val();//备注
var showFlag = $("input[name='showFlag']:checked").val();//是否允许查看投票结果
if(showFlag ==undefined){
showFlag = 0;
}
var anonymousFlag = $("input[name='anonymousFlag']:checked").val();//是否匿名投票
if(anonymousFlag ==undefined){
anonymousFlag = 0;
}
//var state = $('#state').val();//状态
var state = "0";//状态
var companySelectFlag = $("input[name='voterList']:checked").val();//公司
var voterList = [];//投票者
$("#specifiedObject li").each(function(i){
var id = $(this)[0].attributes[1].value;//成员id
var name = $(this)[0].attributes[2].value;//成员名
var waiverFlag = $(this)[0].attributes[3].value;//区分部门(department)和成员(member)
//为部门时(department)则只传部门自己ID
if(waiverFlag == "department"){
voterList[i] = {
wechatDepartmentId: id,
wechatUserName: name
};
//为成员时(member)则成员自己ID和部门自己ID同时上传
}else if(waiverFlag == "member"){
var departmentId = $(this)[0].attributes[4].value;//部门ID(departmentId)
voterList[i] = {
wechatUserId: id,
wechatUserName: name,
wechatDepartmentId: departmentId
}
}
});
// 选择指定部门时,做判断
if(companySelectFlag == 2){
if(voterList == null || voterList.length == 0){
layer.alert('请投票者发送者!', {icon: 0}, function(index){
layer.close(index);
});
return;
}
}

var image = "";//图片添加
$("#pictureAdd3 li img").each(function(){image+=$(this).attr('title') + ",";});
if(voteTitle==""){
layer.alert('请添写投票标题!', {icon: 0}, function(index){
layer.close(index);
$("#voteTitle").focus();
});
return;
}else  if(rule==""){
layer.alert('请添写规则!', {icon: 0}, function(index){
layer.close(index);
$("#rule").focus();
});
return;
}else  if(startDate==""){
layer.alert('请添写开始投票时间!', {icon: 0}, function(index){
layer.close(index);
$("#startDate").focus();
});
return;
}else  if(endDate==""){
layer.alert('请添写结束投票时间!', {icon: 0}, function(index){
layer.close(index);
$("#endDate").focus();
});
return;
}
showMyLoading();
var params = {
voteId: voteId,
voteTitle: voteTitle,
image: image,
rule: rule,
startDate: startDate,
endDate: endDate,
remarks: remarks,
state: state,
companySelectFlag:companySelectFlag,
showFlag:showFlag,
anonymousFlag:anonymousFlag,
voterList: voterList
};
console.log(JSON.stringify(params));
$.ajax({
type: 'POST',
url: API + updateVote,
data: JSON.stringify(params),
timeout:timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
},
success: function (result) {
hideMyLoading();
if (result.success == true) {
layer.msg(updateSuccess, {icon: 6, time: 1000});
} else {
layer.open({title: '温馨提示', content: result.message, icon: 2});
}
},
error: function () {
hideMyLoading();
layer.open({title: '温馨提示', content: serverError, icon: 0});
}
})
}

//基本设置的数据填充
function tabData() {
$('#voteTitle').val(listData3.voteTitle);//投票标题
$('#rule').val(listData3.rule);//规则
$('#state').val(listData3.state);//状态
$('#startDate').val(listData3.startDate);//开始日期
$('#endDate').val(listData3.endDate);//截止日期
$('#image').val(listData3.image);//投票图片
$('#remarks').val(listData3.remarks);//备注

if(listData3.showFlag == 1){
$("#showFlag").attr("checked",true);
}
else {
$("#showFlag").attr("checked",false);
}
if(listData3.anonymousFlag == 1){
$("#anonymousFlag").attr("checked",true);
}
else {
$("#anonymousFlag").attr("checked",false);
}

if(listData3.companySelectFlag == 1){
$('#voterList-1').attr('checked','checked');
console.log(listData3.companySelectFlag);
}
else if(listData3.companySelectFlag == 2){
$('#voterList-2').attr('checked','checked');
if(listData3.voterList!='') {
$('#voterList-2').attr('checked','checked');
$("#specifiedObject").removeClass();
//$("#allCompany").addClass("hidden");
$.each(listData3.voterList, function (i, item) {
var memberId = noNull(item.wechatUserId);
var memberName = noNull(item.wechatUserName);
var departmentId = noNull(item.wechatDepartmentId);
if(memberId!=""){
var waiverFlag = "member";
}else{
memberId = departmentId;
var waiverFlag = "department";
}
if(currentState == 1 || currentState == 2 ){
var $str = '<li class="div_i_b pl-10" name=' + memberId + ' value=' + memberName + ' data-value=' + waiverFlag + ' department-id=' + departmentId + '><span>' + memberName + '</span><i class="icon Hui-iconfont pl-10 pr-10"></i></li>';
}else{
var $str = '<li class="div_i_b pl-10" name=' + memberId + ' value=' + memberName + ' data-value=' + waiverFlag + ' department-id=' + departmentId + '><span>' + memberName + '</span><i class="icon Hui-iconfont pl-10 pr-10" onclick="removeUser($(this))"></i></li>';
}
$("#specifiedObject ul").append($str);
});
}else{
$('#voterList-1').attr('checked','checked');
}
}

}

//被投票者列表查询
function queryballotList() {
//        if (checkIfLogin()==false) return;
var params = {
voteId: voteId,
};
$.ajax({
type: 'POST',
url: API + getVoteCandidateList,
data: JSON.stringify(params),
timeout: timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function (result) {
$('#tbody_data1 tr').remove();//清除表格
if (result.success == true) {
listData = result.data;//表格记录列表
voteCandidateList();//遍历列表数据
//                    var pageCount = Math.ceil(result.maxRank/pageSize);//总页数
$('#totalNumber').html("共" + result.maxRank + "条");//总条数
//                    layer.msg(querySuccess, {icon: 6, time: 1000});
} else {
layer.open({title: '温馨提示', content: result.message, icon: 2});
}
},
error: function () {
layer.open({title: '温馨提示', content: serverError, icon: 0});
}
});
}

//问题列表查询
function queryList(){
//        if (checkIfLogin()==false) return;
var params = {
voteId: voteId,
};
$.ajax({
type: 'POST',
url: API + getQuestionsList,
data: JSON.stringify(params),
timeout: timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function (result) {
$('#tbody_data2 tr').remove();//清除表格
if (result.success == true) {
listData2 = result.data;//表格记录列表
voteList();//遍历列表数据
$('#totalNumber').html("共" + noNull(result.maxRank) + "条");//总条数
//                        layer.msg(querySuccess, {icon: 6, time: 1000});
} else {
layer.open({title: '温馨提示', content: result.message, icon: 2});
}
},
error: function () {
layer.open({title: '温馨提示', content: serverError, icon: 0});
}
});
}

//遍历被投票者列表数据
function voteCandidateList(){
if(listData.length>0) {
$.each(listData, function (i, item) {
$str1 = '';
if(i%2==0){
$str1+="<tr class='text-c '>";
}else{
$str1+="<tr class='text-c tr_bg'>";
}
$str1 += "<td><input type='checkbox' name='checked' value='" + noNull(item.candidateId) + "'/></td>";
$str1 += "<td style='padding-top: 3px;padding-bottom: 3px;'><input class='text-td text-c' style='height: 25px;width: 50px;' name='purchases' type='text' maxlength='3' value='" +noNull(item.candidateOrder) + "' id='" + noNull(item.candidateId) + "'></td>";//排序
$str1 += "<td id='" + noNull(item.voteId) + "'name='"+ noNull(item.candidateId) + "'><a style='cursor:pointer;color:#0066cc' onclick='detailPage($(this),1)'>" + noNull(item.name) + "</a></td>";//姓名
$str1 += "<td>" + noNull(item.resige) + "</td>";//职务
$str1 += "<td>" + noNull(item.image) + "</td>";//照片
$str1 += "<td>" + noNull(item.profiles) + "</td>";//个人简介

if(currentState == 1 || currentState == 2 ){
$str1+='<td>' +
'<div class="operation" style="position: relative;">' +
'<a class="radius size-M form-button"style="color:#0066cc">操作</a></div></td>';
}else{
$str1+='<td>' +
'<div class="operation" style="position: relative;">' +
'<a class="radius size-M form-button"style="color:#0066cc">操作</a></div>' +
'<div class="pop" style="width: 65px;height: 42px;border: solid 1px #cccccc;position: absolute;z-index: 100;margin-left: 20px;background-color: #CCDBE4;">' +
'<a class="radius size-M form-button" style="background-color: #e3fbe3" onclick="detailPage($(this),2)"><i class="icon Hui-iconfont"></i>   修改 </a>' +
'<a class="radius size-M form-button" style="background-color: #e3fbe3" onclick="deleteDetail($(this))"> <i class="icon Hui-iconfont"></i>   删除 </a>' +
'</div>' +
'</td>';
}
$str1 += "</tr>";
$('#tbody_data1').append($str1);
});
}else{
$str1="";
$str1+="<tr class='text-c'>";
$str1+='<td style="text-align:center" colspan="7">暂无数据...</td>';
$str1+="</tr>";
$("#tbody_data1").append($str1);
}
$('#tbody_data1 input[name="purchases"]').attr('onkeyup',integer);
}

//遍历问题列表列表数据
function voteList(){
if(listData2!="") {
$.each(listData2, function (i, item) {
$str2 = '';
if(i%2==0){
$str2+="<tr class='text-c '>";
}else{
$str2+="<tr class='text-c tr_bg'>";
}
$str2 += "<td><input type='checkbox' name='checked' value='" + noNull(item.questionsId) + "'></td>";
$str2 += "<td style='padding-top: 3px;padding-bottom: 3px;'><input class='text-td text-c' style='height: 25px;width: 50px;' name='purchases' type='text' maxlength='3' value='" + noNull(item.questionsOrder) + "' id='" + noNull(item.questionsId) + "'></td>";//排序
$str2 += "<td id='" + noNull(item.voteId) + "'name='"+ noNull(item.questionsId) + "'><a style='cursor:pointer;color:#0066cc' onclick='detailPage2($(this),1)'>" + noNull(item.title) + "</td>";//标题
if(item.questionsDifCode=="1"){
$str2 += "<td>打分</a></td>";//类型
}else if(item.questionsDifCode=="2"){
$str2 += "<td>单选</a></td>";//类型
}else if(item.questionsDifCode=="3"){
$str2 += "<td>多选</a></td>";//类型
}else if(item.questionsDifCode=="4"){
$str2 += "<td>问答</a></td>";//类型
}
//                $str2 += "<td id='" + noNull(item.voteId) + "'name='"+ noNull(item.questionsId) + "'><a style='cursor:pointer;color:#0066cc' onclick='detailPage2($(this),1)'>" + noNull(item.questionsDifCode) + "</a></td>";//类型
$str2 += "<td>" + noNull(item.remarks) + "</td>";//备注
if(currentState == 1 || currentState == 2 ){
$str2+='<td>' +
'<div class="operation" style="position: relative;"><a class="radius size-M form-button" style="color:#0066cc">操作</a></div></td>';
}else{
$str2+='<td>' +
'<div class="operation" style="position: relative;"><a class="radius size-M form-button" style="color:#0066cc">操作</a></div>' +
'<div class="pop" style="width: 65px;height: 42px;border: solid 1px #cccccc;position: absolute;z-index: 100;margin-left: 35px;background-color: #CCDBE4;">' +
'<a class="radius size-M form-button" style="background-color: #e3fbe3" onclick="detailPage2($(this),2)"> <i class="icon Hui-iconfont"></i>   修改 </a>' +
'<a class="radius size-M form-button" style="background-color: #e3fbe3" onclick="deleteDetail2($(this))"> <i class="icon Hui-iconfont"></i>   删除 </a>' +
'</div>' +
'</td>';
}
$str2 += "</tr>";
$('#tbody_data2').append($str2);
});
}else{
$str2="";
$str2+="<tr class='text-c'>";
$str2+='<td style="text-align:center" colspan="6">暂无数据...</td>';
$str2+="</tr>";
$("#tbody_data2").append($str2);
}
$('#tbody_data2 input[name="purchases"]').attr('onkeyup',integer);
}

//问题列表 批量删除
function deteleDetailQuery() {
//        if (checkIfLogin()==false) return;
var questionsList = [];//点击删除ID
var questionsId ="";
var checked = false;//true为有被选中的,false则为一个都没被选中
$('#tbody_data2').each(function(i){
$("#tbody_data2 input:checked").each(function () {
questionsId += $(this).val() + ",";
});
questionsId = questionsId.substring(0, questionsId.length - 1);
if (questionsId.length == 0) {
checked = false;
layer.open({content: '请选择要删除的选项!', icon: 0});
}else{
checked = true;
}
});
if (checked==false) return;
questionsId.split(",").forEach(function(item,i){
questionsList[i]={
questionsId:item
}
});
var params ={
voteId: voteId,
questionsList: questionsList
};
layer.confirm('是否批量删除,请再次确认?', {icon: 3, title: '温馨提示'}, function (index) {
$.ajax({
type: 'POST',
url: API + batchDeleteQuestions,
data: JSON.stringify(params),
timeout: timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
console.log(JSON.stringify(params));
},
success: function (result) {
if (result.success == true) {
updateState = false;
layer.msg(deteleSuccess, {icon: 6, time: 1000});
queryList();
} else {
layer.open({title: '温馨提示',content: result.message,icon : 2});
}
},
error: function () {
layer.open({title: '温馨提示',content:serverError,icon : 0});
}
});
layer.close(index);
});
}

//被投票者 批量删除
function deteleByQuery() {
//        if (checkIfLogin()==false) return;
var candidateList = [];//选中点击删除ID
var candidateId = '';//备用
var checked = false;//true为有被选中的,false则为一个都没被选中
$('#tbody_data1 input[name="checked"]').each(function (i) {
//选出所有被选中项
if($(this)[0].checked == true){
candidateId += $(this).val() + ",";
}
});
if(noNull(candidateId)!=""){
candidateId = candidateId.substring(0, candidateId.length - 1);
candidateId.split(",").forEach(function(item,i){
candidateList[i] = {
candidateId:item
}
})
}
if (candidateList.length == 0) {
checked = false;
layer.open({content: '请选择要删除的选项!', icon: 0});
}else{
checked = true;
}
if (checked==false) return;
var params ={
voteId: voteId,
candidateList: candidateList,
};
layer.confirm('是否批量删除,请再次确认?', {icon: 3, title: '温馨提示'}, function (index) {
$.ajax({
type: 'POST',
url: API + batchDeleteCandidate,
data: JSON.stringify(params),
timeout: timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
console.log(JSON.stringify(params));

},
success: function (result) {
if (result.success == true) {
updateState = false;
layer.msg(deteleSuccess, {icon: 6, time: 1000});
queryballotList();
} else {
layer.open({title: '温馨提示',content: result.message,icon : 2});
}
},
error: function () {
layer.open({title: '温馨提示',content:serverError,icon : 0});
}
});
layer.close(index);
});
}

//问题列表 详情删除
function deleteDetail2(dom){
//if (checkIfLogin()==false) return;
var questionsList = [];//题库详情
var questionsId = dom.parent().parent().parent().children()[1].children[0].id;
questionsList[0]={
questionsId: questionsId,
}
var params ={
voteId: voteId,
questionsList: questionsList
};
layer.confirm('是否删除,请再次确认?', {icon: 3, title: '温馨提示'}, function (index) {
$.ajax({
type: 'POST',
url: API + batchDeleteQuestions,
data: JSON.stringify(params),
timeout: timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
console.log(JSON.stringify(params));
},
success: function (result) {
if (result.success == true) {
updateState = false;
layer.msg(deteleSuccess, {icon: 6, time: 1000});
queryList();
} else {
layer.open({title: '温馨提示',content: result.message,icon : 2});
}
},
error: function () {
layer.open({title: '温馨提示',content:serverError,icon : 0});
}
});
layer.close(index);
});
}

//被投票者 详情删除
function deleteDetail(dom){
//if (checkIfLogin()==false) return;
var candidateList = [];//题库详情
var candidateId = dom.parent().parent().parent().children()[1].children[0].id;
candidateList[0]={
candidateId: candidateId,
}
var params ={
voteId: voteId,
candidateList: candidateList,
};
layer.confirm('是否删除,请再次确认?', {icon: 3, title: '温馨提示'}, function (index) {
$.ajax({
type: 'POST',
url: API + batchDeleteCandidate,
data: JSON.stringify(params),
timeout: timeout,
dataType: 'json',
processData: true,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
console.log(JSON.stringify(params));

},
success: function (result) {
if (result.success == true) {
layer.msg(deteleSuccess, {icon: 6, time: 1000});
queryballotList();
} else {
layer.open({title: '温馨提示',content: result.message,icon : 2});
}
},
error: function () {
layer.open({title: '温馨提示',content:serverError,icon : 0});
}
});
layer.close(index);
});
}

//图片上传
$("#submit").click(function(){
var options  = {
url: API + uploadApk,   //(服务器地址)同action
type: 'post',
beforeSend:function(xhr){//请求之前
var index = layer.load(1, {
shade: [0.5,'#000'] //0.5透明度的黑色背景
});
},
success:function(data){
layer.closeAll('loading');
console.log("响应数据成功!")
//                var pictureName = data.data.file_name;//图片名
var pictureName = data.file_name;//图片名
if(data.success == true || data.status == "ok"){
var $str = "";
$str += "<li class='maskWraper div_i_b picture_size pt-10 pl-10 mb-10' onmousedown='longPressEvent()' onmouseover='floatingLayer()'>";
$str += "<img src='"+ API + pictureName + "' title='" + pictureName + "' class='picture_size'>";
$str += "<a class='maskBar text-c ml-10'>" +
"<i class='Hui-iconfont' title='删除' onclick='deletePicture($(this))'></i>" +
"<i class='Hui-iconfont ml-10' title='原图' onclick='showOriginalPicture($(this))' data-value='"+ API +  pictureName + "'></i>" +
"</a>";
$str += "</li>";
$("#pictureAdd").append($str);
}
},

complete:function(xhr){//请求完成
layer.closeAll('loading');
},
error: function(xhr,status,msg){
console.log("服务器请求失败!")
layer.msg('玩命加载中..');
}
};
$("#addform").ajaxSubmit(options);
})

</script>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: