原文链接:

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>被看&nbsp;<span style="color: #8a2be2;">${(item.countck)!0}</span>&nbsp;被评&nbsp;<span
style="color: red">${(item.countpl)!0}</span>&nbsp;被藏&nbsp;<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>&nbsp;&nbsp;
<select id="s_city" name="s_city" required></select>&nbsp;&nbsp;
<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

公众号二维码:

微信上传图片和图片存储相关推荐

  1. 调用微信上传图片接口和下载图片接口

    目的:调用微信上传图片接口上传图片,并调用下载图片接口下载到本地 1.绑定域名 登录微信公众平台后,进入 公众号设置-->公众号设置页面如图(1),点击设置如图(2),输入域名后,点击保存. 注 ...

  2. 微信上传图片 41005 缺少多媒体文件

    为什么80%的码农都做不了架构师?>>>    微信上传图片,一直报错41005 缺少多媒体文件 查了很多资料,结合 PHP 版本,终于解决了 PHP 版本:5.6.7 $url = ...

  3. 微信开发 --- 调用微信上传图片接口,并保存到自己的服务器

    微信开发 - 调用微信上传图片接口,并保存到自己的服务器 整体思路是这样的: 1.先把手机上的图片上传到微信服务器,然后返回一个图片ID 2.在通过后台根据ID从微信后台拿到流,保存到服务器 前几个步 ...

  4. php微信上传图片之人脸识别

    人脸识别是调用http://apicn.faceplusplus.com中的接口 info.html中的js代码 //引入 <script src="http://res.wx.qq. ...

  5. SpringBoot实现企业微信上传图片

    文章目录 前言 一.上传图片 二.使用步骤 1.引入库 2.实现代码 总结 前言 上传的图片大小限制:图片文件大小应在 5B ~ 2MB 之间 一.上传图片 上传图片得到图片URL,该URL永久有效 ...

  6. 微信上传图片。【代码示例】

    一 准备工作. 一 受限于wx 上传图片时,要getToken ,而调access_token 时,需要加ip 白名单.不然报 invalid signature 出现如下情况,优先考虑ip 白名单问 ...

  7. 微信支付图片上传java_微信开发-----微信公众号调用微信上传图片接口

    $(function () { var url = location.href.split('#')[0]; var date = "url=" + url; //get中url指 ...

  8. php仿微信上传图片压缩,PHP仿微信多图片预览上传实例代码

    生产图片区域,上传按钮#btn可替换自己想要的图片 plupload上传 var uploader = new plupload.Uploader({//创建实例的构造方法 runtimes: 'ht ...

  9. java微信上传图片_微信小程序图片上传java后台(前后端代码)

    小程序代码 upload:function(e){ var that = this; wx.showActionSheet({ itemList: ['从相册选择','拍照'], itemColor: ...

最新文章

  1. 使用RDLC报表向报表传入参数
  2. 另一种公钥私钥认证方式
  3. 炼丹面试官的面试笔记
  4. python启动mysql_Python操作MySQL
  5. 使用EventViewer记录VSTO add-in启动错误
  6. java 常量折叠_深入理解Java虚拟机之早期编译器优化
  7. 参与社团活动的意义_大学参加社团活动有意义吗?
  8. C#打开php链接传参然后接收返回值
  9. pythonic风格_【Python】性能优化之Pythonic风格化代码
  10. R语言的高质量图形渲染库Cairo
  11. U盘越狱iPhone绕ID最新教程及各种坑解决,吐血之作(超详细超简单教程)
  12. 峥果智能连接不到服务器,峥果浴霸 ESP8285版本 固件
  13. 用slmgr命令激活正版Win7旗舰版系统
  14. Error:Execution failed for task :app:mergeDebugResourcesSome file crunching failed的解决方法
  15. 定时炸弹?揭露AmazonBasics电池背后的秘密
  16. 爬取服务器主机信息,魔兽世界怀旧服,基于WclPlayerScore数据二次爬取的各服务器分层人口普查及精英玩家比例...
  17. php doctrine,Doctrine学习笔记 —— 1
  18. 三、自定义Abp Vnext框架代码生成模板
  19. 54/74系列逻辑芯片
  20. 【泡泡图灵智库】基于优化的视觉惯性SLAM与GNSS紧耦合

热门文章

  1. 企业电子招标采购系统源码及功能清单
  2. Nginx在同一台服务器托管两个网站
  3. 用python写web网页实现音乐数据库查询_Python tornado用40行代码搭建数据库交互网页实现快速全栈开发...
  4. 写一个HTML悬浮按钮
  5. js ES2020定义了 BigInt 构造函数
  6. Pathon的基础知识
  7. “湘潭神女”确属违规提拔任用 “神父”遭疯传
  8. e家数据挖掘_总结报告
  9. 新零售的下一个十年,会有什么样的发展?
  10. iOS Layer 图层圆角、边框 、底纹其他操作