image.wxml:
设置两个button,一个进行选择选择图片,另一个进行发布
<form bindsubmit="formSubmit" id='2' bindreset="formReset">
<view class="big-logos">
<button bindtap="upimg">拍照</button>
<block wx:for="{{img_arr}}">
<view class='logoinfo'>
<image src='{{item}}'></image>
</view>
</block>
</view>
<button class='btn' formType="submit">发布</button>
</form>
image.js:(formData传递参数),可以上传多张图片,但是有个bug,每次上传都要调一次接口,有好的解决方案,请指教
var adds = {};
Page({
data: {
img_arr: [],
formdata: '',
},
formSubmit: function (e) {
// var id = e.target.id
// adds = e.detail.value;
// adds.program_id = app.jtappid
// adds.openid = app._openid
// adds.zx_info_id = this.data.zx_info_id
this.upload();
console.log(adds);
},
upload: function () {
var that = this
var imgfile;
for (var i = 0; i < this.data.img_arr.length; i++) {//循环遍历图片
wx.uploadFile({
url: '',//自己的接口地址
filePath: that.data.img_arr[i],
name: 'content',
header: {
"Content-Type": "multipart/form-data",
'accept': 'application/json',
'Authorization': 'okgoodit'//若有token,此处换上你的token,没有的话省略
},
formData:({//上传图片所要携带的参数
userName:"";
}),
success: function (res) {
console.log(res)
if (res) {
console.log("返回的参数信息" + res.data)
wx.showToast({
title: '已提交发布!',
duration: 3000
});
}
}
})
}
this.setData({
username: 'CMOS180404',
password: 'ecb01ff6-2e5c-11e8-b467-0ed5f89f718b'
})
},
upimg: function () {
var that = this;
if (this.data.img_arr.length < 3) {
wx.chooseImage({
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
that.setData({
img_arr: that.data.img_arr.concat(res.tempFilePaths)
});
}
})
} else {
wx.showToast({
title: '最多上传三张图片',
icon: 'loading',
duration: 3000
});
}
},
})
//Java后台接收并解析
package com.lovepet.pet.biz.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.lovepet.pet.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID;
/**
* 图片上传
*
* @author FanChen
* @since 2018年6月1日 上午12:46:29
*/
@Controller
@RequestMapping("/upload")
public class UploadController {
private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
@RequestMapping("/picture")
public void uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
Result result = new Result();
//获取文件需要上传到的路径
File directory = new File("..");
String path = directory.getCanonicalPath() + "\\upload\\";
// 判断存放上传文件的目录是否存在(不存在则创建)
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
logger.debug("path=" + path);
request.setCharacterEncoding("utf-8"); //设置编码
try {
StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
//获取formdata的值
Iterator<String> iterator = req.getFileNames();
String username=request.getParameter("username");
String password=request.getParameter("password");
String timedata=request.getParameter("timedata");
while (iterator.hasNext()) {
MultipartFile file=req.getFile(iterator.next());
//真正写到磁盘上
String uuid=UUID.randomUUID().toString().replace("-","");
String newName=uuid+"."+"jpg";
File file1=new File(path+newName);
OutputStream out=new FileOutputStream(file1);
out.write(file.getBytes());
out.close();
}
} catch (Exception e) {
logger.error("", e);
}
result.setValue(jsonArray);
PrintWriter printWriter = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
printWriter.write(JSON.toJSONString(result));
printWriter.flush();
}
}
本篇文章借鉴了很多前辈的经验,本人也就是个菜鸟,如果有些地方写的不对,请多多指教