原文链接:
http://115.159.110.224:81/ivi/sys/myhref_viewThis.do?f_gid=AC20419796E846D28971C0B3F3D6A612&f_type=ly
1.存储图片文件名到字段,考虑到微信最多上传9张图片,此方法是可取的
2.将图片存储到文件表里,存储上传时对应表的主键。基于如此,给出下面两种方案。
1.存储文件名到字段,用","分割,用list取出。2.接收serverId,循环Id长度,存储Id.jpg图片。
//加入数组签名到对应的链接,使其可以调用微信图片上传接口
public ModelAndView appmylist(HttpServletRequest request, HttpServletResponse response) throws Exception {
String fromuser = request.getParameter("fromuser");
String sd_code = "xxfw"; //信息服务字典
Map<String, Object> model = new HashMap<String, Object>();
Dict dict = new Dict();
dict.setMode("sd_code");
dict.setSd_code(sd_code);
dict.setSd_parent_id("0");
Dict query = dictService.query(dict);
Dict dict2 = new Dict();
dict2.setMode("sd_path");
dict2.setOrder("a.sd_order");
dict2.setSd_path(query.getSd_id());
List<Dict> dictList = dictService.list(dict2);
if (!StringUtil.isEmpty(dictList)) {
for (Dict d : dictList) {
if ("1".equals(d.getSd_child())) {
d.setMode("sd_path");
d.setOrder("a.sd_order");
d.setSd_path(d.getSd_id());
List<Dict> dlist = dictService.list(d);
if (!StringUtil.isEmpty(dlist)) {
d.setDictList(dlist);
}
}
}
}
String s = "http://" + R.dns + "/chatman/msg_appmylist.do?fromuser=" + fromuser;
Actoken ac = actokenService.query(new Actoken());
if (StringUtil.isEmpty(ac)) {
actokenService.create(new Actoken());
ac = actokenService.query(new Actoken());
}
System.out.println("ac.getJs_ticket():" + ac.getJs_ticket());
String signature = CommonUtil.getSignature(ac.getJs_ticket(), s);
System.out.println(" signature:" + signature);
model.put("dList", dictList); ///字典导航
Msg msg = new Msg();
msg.setCreate_user(fromuser);
msg.setMode("create_user");
List<Msg> msgList = msgService.list(msg); //查询今日最新
model.put("signature", signature);
model.put("appId", R.appId);
model.put("msgList", msgList);
model.put("fromuser", fromuser);
return getView(request, model);
}
删除时删除图片:
/**
* 删除临时指令回复记录
*
* @param rl_id 字符串型主键
* @return String
* @throws Exception 异常
*/
@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
public String delete(String rl_id) throws Exception {
Reviewls reviewls = query(rl_id);
if (!StringUtil.isEmpty(reviewls)) {
String fp = reviewls.getRl_pic_path();
if (!StringUtil.isEmpty(fp)) {
String[] fp_str = fp.split(",");
List list = new ArrayList(Arrays.asList(fp_str));
for(int i=0;i<list.size();i++){
if(!StringUtil.isEmpty(list.get(i))){
FileUtil.deleteFile("D:\\Java\\Tomcat6\\webapps\\ROOT\\css\\img/" + list.get(i));
}
}
}
}
return delete(reviewls);
}
html页面ajax分别提交,判断是否上传了图片:
<#include "/WEB-INF/view/macro.ftl"/>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ivi为你服务</title>
<script type="text/javascript" src="${path}/js/JQuery mobile/jquery.js"></script>
<script type="text/javascript" src="${path}/js/jquery_mobile/jquery.mobile-1.4.5.min.map"></script>
<script type="text/javascript" src="${path}/js/expander.min.js"></script>
<script type="text/javascript" src="${path}/js/jquery-latest.min.js"></script>
<script type="text/javascript" src="${path}/js/ajaxupload.3.6.js"></script>
<script type="text/javascript" src="${path}/js/load.js"></script>
<script type="text/javascript" src="${path}/js/area.js"></script>
<script type="text/javascript" src="${path}/js/ajax.js"></script>
<script type="text/javascript" src="${path}/js/JQuery mobile/jquery.mobile-1.4.5.min.js"></script>
<script type="text/javascript" src="${path}/js/jweixin-1.0.0.js"></script>
<link rel="stylesheet" type="text/css" href="${path}/css/expander.css"/>
<link rel="stylesheet" type="text/css" href="${path}/css/theme.css"/>
<link rel="stylesheet" type="text/css" href="${path}/js/JQuery mobile/jquery.mobile-1.4.5.min.css"/>
</head>
<body>
<div data-role="page">
<a href="#contact-info">
<button class="ui-btn ui-icon-plus ui-btn-icon-left ui-shadow ui-corner-all">我要发布</button>
</a>
<div data-role="content">
<ul data-role="listview" data-inset="true" data-theme="e">
<#if msgList??>
<#list msgList as item>
<li><a href="#">
<img src="${path}/images/xxfw/${(item.msg_pic_path)!"pc.jpg"}" width="60" height="60"
style="margin-left:10px;margin-top:15px;">
<span>
<h2> ${(item.msg_title)!""}</h2>
<p>被看 <span style="color: #8a2be2;">${(item.countck)!0}</span> 被评 <span
style="color: red">${(item.countpl)!0}</span> 被藏 <span
style="color:green">${(item.countsc)!0}</span>
</p></a>
<a href="#purchase" data-rel="popup" data-position-to="window"
class="ui-btn ui-icon-gear ui-btn-icon-right ui-shadow ui-corner-all"
data-transition="pop">设置</a>
</span>
</li>
<div data-role="popup" id="purchase" class="ui-content"
style="max-width:340px; padding-bottom:2em;">
<a href="${path}/chatman/msg_appEdit.do?m_id=${item.m_id}"
class="ui-shadow ui-btn ui-corner-all ui-btn-b ui-icon-edit ui-btn-icon-left ui-btn-inline ui-mini">修改</a>
<a href="#" οnclick="down('${item.m_id}')"
class="ui-shadow ui-btn ui-corner-all ui-btn-b ui-icon-delete ui-btn-icon-left ui-btn-inline ui-mini">删除</a>
</div>
<li>
<!-- TODO -->
<a href="${path}/chatman/msg_detail.do?m_id=${(item.m_id)}&openid=${fromuser}"
class="ui-btn ui-icon-eye ui-btn-icon-right ui-shadow ui-corner-all">
<p>${(item.msg_address)!}</p>
<p>所属:${item.msg_type_des}</p>
<p><@dateOut item.create_time></@></p>
</a>
</li>
</#list>
</#if>
</ul>
</div>
<div data-role="footer">
</div>
</div>
<!-- Second Page -->
<div data-role="page" id="contact-info" data-title="信息服务">
<div data-role="header">
<h1>添加信息</h1>
</div>
<div data-role="content">
<p><span style="color: red">说明:</span>添加此类服务:1.请将信息填写完整 2.不得填写违规信息,否则将删除信息</p>
<form method="post" name="form" id="form">
<div data-role="content" data-role="fieldcontain">
<label for="address">所属位置:</label>
<select id="s_province" name="s_province" required></select>
<select id="s_city" name="s_city" required></select>
<select id="s_county" name="s_county" required></select>
<script type="text/javascript" src="area.js"></script>
<script type="text/javascript">_init_area();</script>
<label for="address">具体街道:</label>
<input type="text" id="address" name="address" required>
<label for="msg_title">标题:</label>
<input type="text" id="msg_title" name="msg_title" class="w320 " maxlength="20" required>
<label for="msg_type">所属类目:</label>
<select name="msg_type" id="msg_type" <#--multiple="multiple"--> data-native-menu="false"
data-icon="grid"
data-iconpos="right">
<#if dList??>
<#list dList as ditem>
<#if ditem.dictList ??>
<optgroup label="${ditem.sd_description}">
<#list ditem.dictList as item>
<option value="${item.sd_id}">${item.sd_description}</option>
</#list>
</optgroup>
<#else>
<option value="${ditem.sd_id}">${ditem.sd_description}</option>
</#if>
</#list>
</#if>
</select>
<label>内容:</label>
<textarea cols="40" rows="8" name="content" id="content" data-max="500" data-min="5"
required></textarea>
<br>
<div>添加相关图片<a href="#" data-role="button" data-icon="plus" id="chooseImage"
data-iconpos="notext">服务相关图片</a></div>
<div id="imgzip" class="wxapi_index_container"></div>
<div>
<a οnclick="save()"><input type="submit" data-inline="true" value="保存"></a>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
jQuery.mobile.ajaxEnabled = false;
});
var Gid = document.getElementById;
var showArea = function() {
Gid('show').innerHTML = "<h3>" + Gid('s_province').value + " - " +
Gid('s_city').value + " - " +
Gid('s_county').value + "</h3>"
}
var url = '${path}/chatman/msg_appmylist.do?fromuser=${fromuser}';
var temp = 0;
var images = {
localId: [],
serverId: []
};
setTimeout(function() {
document.querySelector('#chooseImage').onclick = function () {
temp = 1;
wx.chooseImage({
success: function (res) {
images.localId = res.localIds;
var html = '';
for (var i = 0; i < images.localId.length; i++) {
html += '<img width="100" height="100" src="' + images.localId[i] + '">';
}
document.querySelector('#imgzip').innerHTML = html;
alert('已选择 ' + res.localIds.length + ' 张图片');
}
});
};
}, 3000);
function save() {
var fromuser = '${fromuser}';
var s_province = $("#s_province").val();
var s_city = $("#s_city").val();
var s_county = $("#s_county").val();
var address = $("#address").val();
var msg_title = $("#msg_title").val();
var msg_type = $("#msg_type").val();
var content = $("#content").val();
/* if (validate()) {*/
if (0 == temp) {
$.ajax({
url:'${path}/chatman/msg_mySave.do',// 跳转到 action
data: {
serverId: "" ,
fromuser:fromuser,
s_province:s_province,
s_city:s_city,
s_county:s_county,
address:address,
msg_title:msg_title,
msg_type:msg_type,
content:content
},
type:'post',
cache:false,
success:function(result) {
//alert("已加入服务,审核后显示!");
// refreshPage(); TODO?
if (confirm("信息已提交,返回查看。")) {
//history.go(-1);
document.location.href = url;
} else {
document.location.href = url;
// history.go(-1);
}
},
error : function() {
alert("异常!");
}
});
} else if (1 == temp) {
doupload();
}
}
function doupload() {
var fromuser = '${fromuser}';
var s_province = $("#s_province").val();
var s_city = $("#s_city").val();
var s_county = $("#s_county").val();
var address = $("#address").val();
var msg_title = $("#msg_title").val();
var msg_type = $("#msg_type").val();
var content = $("#content").val();
var i = 0, length = images.localId.length;
images.serverId = [];
function upload() {
wx.uploadImage({
localId: images.localId[i],
isShowProgressTips:1,
success: function (res) {
i++;
images.serverId.push(res.serverId);
if (i < length) {
upload();
} else {
$.ajax(
{
type: "post",
url:'${path}/chatman/msg_mySave.do',// 跳转到 action
data: {
serverId: images.serverId.join(",") ,
fromuser:fromuser,
s_province:s_province,
s_city:s_city,
s_county:s_county,
address:address,
msg_title:msg_title,
msg_type:msg_type,
content:content
},
async: true,
success:function(result) {
if (confirm("信息已提交,返回查看。")) {
document.location.href = url;
} else {
document.location.href = url;
}
//refreshPage(); TODO?
},
error : function() {
alert("异常!");
}
});
}
},
fail: function (res) {
}
});
}
upload();
}
wx.config({
debug: false,
appId: '${appId}',
timestamp: 1414587457,
nonceStr: 'Wm3WZYTPz0wzccnW',
signature: '${(signature)!}',
jsApiList: [
'chooseImage',
'uploadImage',
'openLocation',
'getLocation'
]
});
var index = 0;
var timeout = setInterval(function () {
if (index > 10) {
window.clearInterval(timeout)
}
$("article").eq(index).addClass("show");
index++
}, 300);
function showFoo() {
$("#fooId").trigger("expand");
}
$("#expandSettings").on("click", function () {
if ($("ul.settings").hasClass("open")) {
$("ul.settings").removeClass("open");
} else {
$("ul.settings").addClass("open");
}
});
function down(m_id) {
alert("信息已移除!")
$.ajaxPost("${path}/chatman/msg_down.do", {"m_id":m_id}, function(result) {
if ("1" == result) {
window.location = url;
return false;
}
});
}
</script>
</body>
</html>
提交的代码到后台保存:
public ModelAndView mySave(HttpServletRequest request, HttpServletResponse response) throws Exception {
String serverId1 = request.getParameter("serverId");
String fromuser = request.getParameter("fromuser");
String s_province = request.getParameter("s_province");
String s_city = request.getParameter("s_city");
String s_county = request.getParameter("s_county");
String address = "" + s_province + s_city + s_county + request.getParameter("address");
String msg_title = request.getParameter("msg_title");
String msg_type = request.getParameter("msg_type");
String content = request.getParameter("content");
Msg msg = new Msg();
msg.setMsg_type(msg_type);
msg.setMsg_title(msg_title);
msg.setContent(content);
msg.setMsg_address(address);
msg.setCreate_user(fromuser);
msg.setCreate_time(new Date());
String s = "";
//将图片上传到微信服务器上,在从微信服务器上获取图片到本地服务器,存储图片地址到数据库
if (!StringUtil.isEmpty(serverId1)) {
String[] serverId = serverId1.split(",");
System.out.println("服务器serverId:-------");
System.out.println(serverId1);
Actoken ac = actokenService.query(new Actoken());
if (!StringUtil.isEmpty(serverId)) {
for (String mediaId : serverId) {
//filePath 文件存储路径的扩展名
String filePath = CommonUtil.getMeida(ac.getAccesstoken(), mediaId, getServletContext().getRealPath("/css/img"));
System.out.println("filePath---" + filePath);
if (!StringUtil.isEmpty(filePath)) {
filePath = filePath.replace("D:\\Java\\Tomcat6\\webapps\\iFrame\\css\\img/", "");
s += filePath + ","; //以文件扩展名存入数据库 用,隔开 D:\Java\Tomcat6\webapps\iFrame\css\img/
}
}
}
}
if (!StringUtil.isEmpty(s)) {
msg.setMsg_pic(s);
System.out.println("设置图片路径成功!图片路径为:" + s);
}
String result = msgService.create(msg);
return responseText(response, result);
}
取出图片,设置到图片List里
@ActionAnnotation(name = "信息站台详细", group = "查询")
public ModelAndView view(HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model = new HashMap<String, Object>();
Msg msg = msgService.query(request.getParameter("m_id"));
List glist = new ArrayList();
String pic_path = msg.getMsg_pic();
if (!StringUtil.isEmpty(pic_path)) {
String[] fp_str = pic_path.split(",");
glist = new ArrayList(Arrays.asList(fp_str));
}
model.put("msg", msg);
model.put("glist", glist);
return getView(request, model);
}
<tr>
<td class="th">相关图片</td>
<td class="td" colspan="3"> <#if glist ??>
<#list glist as item>
<img src="${path}/css/img/${item}" width="100px" height="100px" >
</#list>
</#if></td>
</tr>
方法2:
public ModelAndView addSupplySave(HttpServletRequest request, HttpServletResponse response) throws Exception {
String token = request.getParameter("token"); String create_user = request.getParameter("create_user");
String fs_name = request.getParameter("fs_name");
String fs_count = request.getParameter("fs_count");
String fs_price = request.getParameter("fs_price");
String comment = request.getParameter("comment");
String fs_measurement = request.getParameter("fs_measurement");
String serverId1 = request.getParameter("serverId");
String[] serverId = null;
if(!StringUtil.isEmpty(serverId1)){
serverId = request.getParameter("serverId").split(",");
}
Supply supply = new Supply();
supply.setCreate_time(new Date());
supply.setComment(comment);
supply.setCreate_user(create_user);
supply.setFs_name(fs_name);
supply.setFs_count( Float.parseFloat(fs_count));
supply.setFs_price(Double.parseDouble(fs_price));
supply.setFs_measurement(fs_measurement);
supplyService.create(supply, serverId, token);
return responseText(response,"1");
}
@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
public void create(Supply supply, String[] serverId, String token) throws Exception {
String fs_id = create(supply);
if (!StringUtil.isEmpty(serverId)) {
for (String mediaId : serverId) {
String path = WeiXinUtil.getMeida(token, mediaId, getServletContext().getRealPath("/image"));
if (!StringUtil.isEmpty(path)) {
Files files = new Files();
files.setSf_infoid(fs_id);
files.setSf_table(Supply.table_name);
files.setSf_name(mediaId + ".jpg");
sqlDao.create("sys_file.create", files);
}
}
}
}
查看时,获取List,设为属性:
public List<Supply> list(Supply supply) throws Exception {
List<Supply> supplyList = sqlDao.list("farm_supply.query", supply);
if (!StringUtil.isEmpty(supplyList)) {
for (Supply s : supplyList) {
List<Files> filesList = sqlDao.list("sys_file.query",new Files("sf_infoid",s.getFs_id()));
s.setFilesList(filesList);
}
}
return supplyList;
}
大家可参考我的博客:
我的博客:115.159.110.224
我的微信公众号:my528xx
公众号二维码: