需求描述:因ajaxFileUpload 文件上传插件是异步请求,但是业务上需要先得到 ajaxFileUpload 请求后的图片url, 在通过ajax 把图片URL等其它需要录入的数据一并写入数据库,6张图片是按用户自己需求可传可不传,我们要保证的是无论用户传的是哪张图片或不传图片,我们都要把数据写入数据库;这里我们用到了 $.Deferred();$.when(); ajaxtime.resolve(); setInterval ()来确定ajaxFileUpload是否完成了图片上传,因为不确定用户上传多少张图片,所以我们定义两个变量 FF 与 X,一个记录用户上传的图片数量,一个记录上传成功的图片数量;通过setInterval 每个3秒进行对比一次,对比成功做 ajaxtime.resolve()标记;同时清除轮询延时器,通过its_promiseTime.done(function () { });函数调用信息写入函数createGasCylinderchkInfo();
定义6个 ajaxFileUpload 函数图片上传,一次上传6张;
页面:
/*(产品合格证)*/
td1 =
"<div class=\"img-box full\">" +
"<section class=\" img-section\">" +
" <p class=\"up-p\">产品合格证:<span class=\"up-span\">最多可
以上传5张图片</span></p>" +
"<div class=\"z_photo upimg-div clear\" >" +
"<section class=\"z_file fl\">" +
"<img src=\"/assets/upjs/img/a11.png\" class=\"add-img\">" +
"<input type=\"file\" name=\"file\"
id=\"productqualifyurlFile1\" class=\"file\" value=\"\"
accept=\"image/jpg,image/jpeg,image/png,image/bmp\" multiple />" +
"</section>" +
"</div>" +
"</section>" +
"</div>";
/*(质量证明书)*/
td2 =
"<div class=\"img-box full\">" +
"<section class=\" img-section\">" +
"<p class=\"up-p\">质量证书:<span class=\"up-span\">最多可以上传5张图片</span></p>" +
"<div class=\"z_photo upimg-div clear\" >" +
"<section class=\"z_file fl\">" +
"<img src=\"/assets/upjs/img/a11.png\" class=\"add-img\">" +
"<input type=\"file\" name=\"file\" id=\"qualitycertificateurlFile2\" class=\"file\" value=\"\" accept=\"image/jpg,image/jpeg,image/png,image/bmp\" multiple />" +
"</section>" +
"</div>" +
"</section>" +
"</div>";
/*(质量说明书)*/
td3 =
"<div class=\"img-box full\">" +
"<section class=\" img-section\">" +
"<p class=\"up-p\">质量说明书:<span class=\"up-span\">最多可以上传5张图片</span></p>" +
"<div class=\"z_photo upimg-div clear\" >" +
"<section class=\"z_file fl\">" +
"<img src=\"/assets/upjs/img/a11.png\" class=\"add-img\">" +
"<input type=\"file\" name=\"file\" id=\"manufacturingSupervisIoninsurFile2\" class=\"file\" value=\"\" accept=\"image/jpg,image/jpeg,image/png,image/bmp\" multiple />" +
"</section>" +
"</div>" +
"</section>" +
"</div>";
/*(使用说明书)*/
td4 =
"<div class=\"img-box full\">" +
"<section class=\" img-section\">" +
" <p class=\"up-p\">使用说明书:<span class=\"up-span\">最多可以上传5张图片</span></p>" +
"<div class=\"z_photo upimg-div clear\" >" +
"<section class=\"z_file fl\">" +
"<img src=\"/assets/upjs/img/a11.png\" class=\"add-img\">" +
"<input type=\"file\" name=\"file\" id=\"instructionmanualurlFile2\" class=\"file\" value=\"\" accept=\"image/jpg,image/jpeg,image/png,image/bmp\" multiple />" +
"</section>" +
"</div>" +
"</section>" +
"</div>";
/*(检验报告)*/
td5 =
"<div class=\"img-box full\">" +
"<section class=\" img-section\">" +
"<p class=\"up-p\">检验报告:<span class=\"up-span\">最多可以上传5张图片</span></p>" +
"<div class=\"z_photo upimg-div clear\" >" +
"<section class=\"z_file fl\">" +
"<img src=\"/assets/upjs/img/a11.png\" class=\"add-img\">" +
"<input type=\"file\" name=\"file\" id=\"inspectereporturlFile2\" class=\"file\" value=\"\" accept=\"image/jpg,image/jpeg,image/png,image/bmp\" multiple />" +
"</section>" +
"</div>" +
"</section>" +
"</div>";
/*(日常检验记录)*/
td6 =
"<div class=\"img-box full\">" +
"<section class=\" img-section\">" +
"<p class=\"up-p\">日常检验记录:<span class=\"up-span\">最多可以上传5张图片</span></p>" +
"<div class=\"z_photo upimg-div clear\" >" +
"<section class=\"z_file fl\">" +
"<img src=\"/assets/upjs/img/a11.png\" class=\"add-img\">" +
"<input type=\"file\" name=\"file\" id=\"dailyinspectrecordurlFile2\" class=\"file\" value=\"\" accept=\"image/jpg,image/jpeg,image/png,image/bmp\" multiple />" +
"</section>" +
"</div>" +
"</section>" +
"</div>";
/*新增必须isfirsttest 写1*/
$("#isfirsttest").val(1);
/*产品合格证*/
$("#productqualifyurldurlHtml").html(td1);
/*质量证书*/
$("#qualitycertificateurlHtml").html(td2);
/*质量说明书*/
$("#manufacturingsupervisioninsurlHtml").html(td3);
/*使用说明书*/
$("#instructionmanualurlHtml").html(td4);
/*检验报告*/
$("#inspectereporturldurlHtml").html(td5);
/*日常检验记录*/
$("#dailyinspectrecordurlHtml").html(td6);
定义 ajaxFileUpload 图片上传函数:
/*================================================实现数据库图片上传==================================================================*/
/*产品合格证*/
function ProductqualifyurlFileUpload(someAjaxDfd) {
/*产品合格证*/
$.ajaxFileUpload({
url: "/config/create-AllGasCylinderCheckInfoFileurlFileUpload",
fileElementId: 'productqualifyurlFile1',
dataType: "json",
success: function (data) {
if (data.resultCode == 200) {
//把得到的图片url写入inputy隐藏域
$("#productqualifyurl").val(data.fieldString);
}
if (data.resultCode == 505) {
DJMask.msg("请图片上传失败");
}
//标记ajaxFileUpload执行完成
someAjaxDfd.resolve();
},
error: function () {
}
});
}
/*质量证书*/
function qualitycertificateurlFileUpload(ajax1Dfd) {
/*质量证书*/
$.ajaxFileUpload({
url: "/config/create-AllGasCylinderCheckInfoFileurlFileUpload",
fileElementId: 'qualitycertificateurlFile2',
dataType: "json",
success: function (data) {
if (data.resultCode == 200) {
//把得到的图片url写入inputy隐藏域
$("#qualitycertificateurl").val(data.fieldString);
}
if(data.resultCode == 505){
DJMask.msg("请图片上传失败");
}
//标记ajaxFileUpload执行完成
ajax1Dfd.resolve();
},
error: function () {
DJMask.msg("请图片上传失败");
}
});
}
/* 质量说明书*/
function ManufacturingSupervisionInsurFileUpload(ajax2Dfd) {
/* 质量说明书*/
$.ajaxFileUpload({
url: "/config/create-AllGasCylinderCheckInfoFileurlFileUpload",
fileElementId: 'manufacturingSupervisIoninsurFile2',
dataType: "json",
success: function (data) {
if (data.resultCode == 200) {
//把得到的图片url写入inputy隐藏域
$("#manufacturingsupervisioninsurl").val(data.fieldString);
}
if(data.resultCode == 505){
DJMask.msg("请图片上传失败");
}
//标记ajaxFileUpload执行完成
ajax2Dfd.resolve();
},
error: function () {
DJMask.msg("请图片上传失败");
}
});
}
/* 使用说明书*/
function instructionmanualurlFileUpload(ajax3Dfd) {
/* 使用说明书*/
$.ajaxFileUpload({
url: "/config/create-AllGasCylinderCheckInfoFileurlFileUpload",
fileElementId: 'instructionmanualurlFile2',
dataType: "json",
success: function (data) {
if (data.resultCode == 200) {
//把得到的图片url写入inputy隐藏域
$("#instructionmanualurl").val(data.fieldString);
}
if(data.resultCode == 505){
DJMask.msg("请图片上传失败");
}
//标记ajaxFileUpload执行完成
ajax3Dfd.resolve();
},
error: function () {
DJMask.msg("请图片上传失败");
}
});
}
/* 检验报告*/
function InspectereporturlUpload(ajax4Dfd) {
/* 检验报告*/
$.ajaxFileUpload({
url: "/config/create-AllGasCylinderCheckInfoFileurlFileUpload",
fileElementId: 'inspectereporturlFile2',
dataType: "json",
success: function (data) {
if (data.resultCode == 200) {
//把得到的图片url写入inputy隐藏域
$("#inspectereporturl").val(data.fieldString);
}
if(data.resultCode == 505){
DJMask.msg("请图片上传失败");
}
//标记ajaxFileUpload执行完成
ajax4Dfd.resolve();
},
error: function () {
DJMask.msg("请图片上传失败");
}
});
}
/* 日常检验记录*/
function DailyinspectrecordurlUpload(ajax5Dfd) {
/* 日常检验记录*/
$.ajaxFileUpload({
url: "/config/create-AllGasCylinderCheckInfoFileurlFileUpload",
fileElementId: 'dailyinspectrecordurlFile2',
dataType: "json",
success: function (data) {
if (data.resultCode == 200) {
//把得到的图片url写入inputy隐藏域
$("#dailyinspectrecordurl").val(data.fieldString);
}
if(data.resultCode == 505){
DJMask.msg("请图片上传失败");
}
//标记ajaxFileUpload执行完成
ajax5Dfd.resolve();
},
error: function () {
DJMask.msg("请图片上传失败");
}
});
}
页面Input隐藏域存取图片上传完成的图片url:
<form class="am-form am-form-horizontal" action="##" method="post"
id="stuForm">
<input id="gasCylinderCheckInfoId" name="gasCylinderCheckInfoId"
type="hidden" value="">
<%--第一次添加为1,第二次添加为0--%>
<input id="isfirsttest" name="isfirsttest" type="hidden" value="">
<%--产品合格证--%>
<input type="hidden" id="productqualifyurl" name="productqualifyurl"
value="">
<%--质量证书--%>
<input type="hidden" id="qualitycertificateurl" name="productqualifyurl"
value="">
<%--质量说明书--%>
<input type="hidden" id="manufacturingsupervisioninsurl"
name="productqualifyurl" value="">
<%--使用说明书--%>
<input type="hidden" id="instructionmanualurl" name="productqualifyurl"
value="">
<%--检验报告--%>
<input type="hidden" id="inspectereporturl" name="productqualifyurl"
value="">
<%--日常检验记录--%>
<input type="hidden" id="dailyinspectrecordurl" name="productqualifyurl"
value="">
定义实现数据写入数据库,包括存入图片上传后得到的url;
/* 添加信息*/
function createGasCylinderchkInfo(cph) {
//从Inputy隐藏域中获取产品合格证图片url
var productqualifyurl = $("#productqualifyurl").val();
//从Inputy隐藏域中获取质量证书图片url
var qualitycertificateurl = $("#qualitycertificateurl").val();
//从Inputy隐藏域中获取质量说明书图片url
var manufacturingsupervisioninsurl = $("#manufacturingsupervisioninsurl").val();
//从Inputy隐藏域中获取使用说明书图片url
var instructionmanualurl = $("#instructionmanualurl").val();
//从Inputy隐藏域中获取检验报告图片url
var inspectereporturl = $("#inspectereporturl").val();
//从Inputy隐藏域中获取日常检验记录图片url
var dailyinspectrecordurl = $("#dailyinspectrecordurl").val();
var num = $("#num").val();
var GasCylinderNum = $("#GasCylinderNum").val();
var positionnum = $("#positionnum").val();
var orderByClause = $("#orderByClause").val();
var isfirsttest = $("#isfirsttest").val();
var testdate = $("#testdate").val();
var testunit = $("#testunit").val();
var testresult = $("#testresult").val();
console.log("确认啦");
$.ajax({
type: "POST",
dataType: "json",
async:false,
url: "/config/add-GasCylinderCheckInfo",//url
data: {
"productqualifyurl": productqualifyurl,
"qualitycertificateurl": qualitycertificateurl,
"manufacturingsupervisioninsurl": manufacturingsupervisioninsurl,
"instructionmanualurl": instructionmanualurl,
"inspectereporturl": inspectereporturl,
"dailyinspectrecordurl": dailyinspectrecordurl,
"num": num,
"cph": cph,
"GasCylinderNum": GasCylinderNum,
"positionnum": positionnum,
"orderByClause": orderByClause,
"isfirsttest": isfirsttest,
"testdate": testdate,
"testunit": testunit,
"testresult": testresult
},
/*data: $("#stuForm").serialize(),*/
success: function (data) {
console.log("ajax:" + data);
if (data.resultCode == 200) {
$("#messageValue").val(data.failDesc);
$("#btn2").click();
}
if (data.resultCode == 505) {
$("#messageValue").val(data.failDesc);
$("#btn3").click();
}
;
},
error: function () {
$("#messageValue").val("系统异常操作不成功!\n");
$("#btn3").click();
}
});
}
定义执行方法 同步执行所有的 ajaxFileUpload与ajax请求:
$(function () {
$("#btn1").click(function () {
var cph = $("#cph").val();
var num = $("#num").val();
var firsttestdate = $("#testdate").val();
var firsttestunit = $("#testunit").val();
var firsttestresult = $("#testresult").val();
if (0 == cph.length || 0 == num.length || 0 == firsttestdate.length || 0 ==
firsttestunit.length ||
0 == firsttestresult.length) {
DJMask.msg("请将数据填写完整!");
return;
}
/*================图片上传获得图片id=================*/
/*===============先上传图片=========================*/
var f1 = document.getElementById("productqualifyurlFile1").value;
var f2 = document.getElementById("qualitycertificateurlFile2").value;
var f3 = document.getElementById("manufacturingSupervisIoninsurFile2").value;
var f4 = document.getElementById("instructionmanualurlFile2").value;
var f5 = document.getElementById("inspectereporturlFile2").value;
var f6 = document.getElementById("dailyinspectrecordurlFile2").value;
/*=============ajax图片上传===========================*/
var txt = "确定为车牌号: " + cph + " 添加定检信息?";
var option = {
title: "添加定检信息",
btn: parseInt("0011", 2),
onOk: function () {
console.log("确认啦");
DJMask.msg("正在处理请稍等!");
var someAjaxDfd = $.Deferred();
var ajax1Dfd = $.Deferred();
var ajax2Dfd = $.Deferred();
var ajax3Dfd = $.Deferred();
var ajax4Dfd = $.Deferred();
var ajax5Dfd = $.Deferred();
var ajaxtime = $.Deferred();
// 返回这个延迟对象的Promise
/*产品合格证*/
var its_promise = $.when(someAjaxDfd);
/*质量证书*/
var its_promise1 = $.when(ajax1Dfd);
/* 质量说明书*/
var its_promise2 = $.when(ajax2Dfd);
/* 使用说明书*/
var its_promise3 = $.when(ajax3Dfd);
/* 检验报告*/
var its_promise4 = $.when(ajax4Dfd);
/* 日常检验记录*/
var its_promise5 = $.when(ajax5Dfd);
/* 添加数据*/
var its_promiseTime = $.when(ajaxtime);
//纪录用户需要上传的图片数量
var FF = 0;
//纪录上传成功的图片数量
var x = 0;
/*======================新方法=================================*/
if (null != f1 && f1 != ""){
if ((!/\.(|jpg|jpeg|png|JPG|PNG)$/.test(f1)) ) {
DJMask.msg("图片类型必须是.jpeg,jpg,png中的一种");
return false;
}
FF++;
/*产品合格证*/
ProductqualifyurlFileUpload(someAjaxDfd);
its_promise.done(function () {
x++;
});
}
if (null != f2 && f2 != ""){
if ((!/\.(|jpg|jpeg|png|JPG|PNG)$/.test(f2)) ) {
DJMask.msg("图片类型必须是.jpeg,jpg,png中的一种");
return false;
}
FF++;
/*质量证书*/
qualitycertificateurlFileUpload(ajax1Dfd);
its_promise1.done(function () {
x++;
});
}
if (null != f3 && f3 != ""){
if ((!/\.(|jpg|jpeg|png|JPG|PNG)$/.test(f3)) ) {
DJMask.msg("图片类型必须是.jpeg,jpg,png中的一种");
return false;
}
FF++;
/* 质量说明书*/
ManufacturingSupervisionInsurFileUpload(ajax2Dfd);
its_promise2.done(function () {
x++;
});
}
if (null != f4 && f4 != ""){
if ((!/\.(|jpg|jpeg|png|JPG|PNG)$/.test(f4)) ) {
DJMask.msg("图片类型必须是.jpeg,jpg,png中的一种");
return false;
}
FF++;
/* 使用说明书*/
instructionmanualurlFileUpload(ajax3Dfd);
its_promise3.done(function () {
x++;
});
}
if (null != f5 && f5 != ""){
if ((!/\.(|jpg|jpeg|png|JPG|PNG)$/.test(f5)) ) {
DJMask.msg("图片类型必须是.jpeg,jpg,png中的一种");
return false;
}
FF++;
/* 检验报告*/
InspectereporturlUpload(ajax4Dfd);
its_promise4.done(function () {
x++;
});
}
if (null != f6 && f6 != ""){
if ((!/\.(|jpg|jpeg|png|JPG|PNG)$/.test(f6)) ) {
DJMask.msg("图片类型必须是.jpeg,jpg,png中的一种");
return false;
}
FF++;
/* 日常检验记录*/
DailyinspectrecordurlUpload(ajax5Dfd);
its_promise5.done(function () {
x++;
});
}
//通过定时循环 不断的去判断 上传图片数量与图片上传成功数量
var time = setInterval(function () {
//数量一致表示图片全部上传成功
if(FF == x){
//通过此变量标记,调用its_promiseTime.done函数执行信息写入函数
ajaxtime.resolve();
//任务完成清除时间,停止轮询
clearTimeout(time);
}
},3000);
//等待图片上传结束信号,调用信息数据写入函数,写入数据;
its_promiseTime.done(function () {
/信息数据写入*/
createGasCylinderchkInfo(cph);
});
}
}
window.wxc.xcConfirm(txt, "custom", option);
});
后台代码,图片储存于阿里oss对象服务器上,图片上传成功后返回图片URL放入页面input隐藏域中,多张图片会用逗号进行拼接。【注:URL不会通过此方法写入数据库】
/**
* 文件上传
*/
@RequestMapping(value = "/config/create-AllGasCylinderCheckInfoFileurlFileUpload", method = RequestMethod.POST)
@ResponseBody
public Page AllGasCylinderCheckInfoProductqualifyurlFileUpload(
@RequestParam("file") List<CommonsMultipartFile> files,
HttpServletRequest request) throws IOException
{
String CALLER = "GasCylinderCheckInfoController_/config/create-AllGasCylinderCheckInfoFileurlFileUpload ";
String startTime = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
String fileName = "";
String fileType = "";
Page page = new Page();
String urls = "";
try
{
if (null != files && 0 < files.size())
{
for (int i = 0; i < files.size(); i++)
{
if (!files.get(i).isEmpty())
{
// 文件保存路径
CommonsMultipartFile file = (CommonsMultipartFile) files
.get(i);
fileName = file.getOriginalFilename();
if (null != fileName && 0 < fileName.length())
{
fileType = fileName
.substring(fileName.lastIndexOf(".") + 1);
}
String url = OSSUploadUtil.uploadFile(file, fileType);
if (null != url && 0 < url.length())
{
urls += url + ",";
}
else
{
page.setFailDesc("图片上传不成功!");
page.setResultCode(505);
}
}
}
if (null != urls && 0 < urls.length())
{
page.setFieldString(urls);
page.setFailDesc("图片上传成功!");
page.setResultCode(200);
}
}
else
{
page.setFailDesc("未获取到文件信息!");
page.setResultCode(505);
}
}
catch (Exception e)
{
e.printStackTrace();
BaseController.saveLog(
SecurityUtils.getSubject().getPrincipals().toString(),
startTime, DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss"),
BaseController.getRequestIp(request), "气瓶信息", "气瓶定检信息",
"增加气瓶定检信息/文件上传", 0, 1, "系统异常文件上传失败!" + CALLER);
}
finally
{
return page;
}
}