简单来说是先执行upload到后台,controller将图片保存到服务器后将图片路径通过json返回小程序,在upload sucess时setData存储路径。然后调用wx.request。
下面,我用一个发布文章的代码来演示,小程序端wxml文件如下:
<!--pages/productReleased/productReleased.wxml-->
<!--文章发布-->
<view>
文章发布
</view>
<form bindsubmit="formSubmit">
<!--文章标题-->
<view class='title'>
<view class='title_text'>
<text>文章标题:</text>
<input name="biaoti" type='text' value='{{biaoti}}' bindblur='titleBlur'></input>
</view>
</view>
<!--文章内容-->
<view class='title'>
<view class='title_text'>
<text>文章内容:</text>
<input name="neirong" type='text' value='{{neirong}}' bindblur='priceBlur'></input>
</view>
</view>
<!--文章作者-->
<view class='info-point'>
<view class='title_text'>
<text>文章作者:</text>
<textarea name="zuozhe" class='textarea' value='{{zuozhe}}' bindblur='infoBlur'></textarea>
</view>
</view>
<!--文章分类-->
<view class='info-point'>
<view class='title_text'>
<text>文章分类:</text>
<textarea name="fenlei" class='textarea' value='{{fenlei}}' bindblur='pointBlur'></textarea>
</view>
</view>
<!--文章链接-->
<view class='title'>
<view class='title_text'>
<text>文章链接:</text>
<textarea name="lianjie" class='textarea' value='{{lianjie}}' bindblur='pointBlur'></textarea>
</view>
</view>
<!--文章备注-->
<view class='title'>
<view class='title_text'>
<text>文章备注:</text>
<textarea name="beizhu" class='textarea' value='{{beizhu}}' bindblur='pointBlur'></textarea>
</view>
</view>
<!--文章顺序-->
<view class='title'>
<view class='title_text'>
<text>文章顺序:</text>
<textarea name="shunxu" class='textarea' value='{{shunxu}}' bindblur='pointBlur'></textarea>
</view>
</view>
<view class='tu1'>
<block wx:for="{{img_arr}}" wx:key="index">
<view class='logoinfo'>
<image class='logoinfo' mode="aspectFill" src='{{item}}' data-index="{{index}}" bindtap="previewImg" bindlongpress="deleteImg" name="headimage" ></image>
</view>
</block>
<image bindtap='upimg' class='tu' src="../images/x21.jpg"></image> </view>
<button form-type='submit' class='sureRelease'>确认发布</button>
</form>
小程序端js文件如下:
const app = getApp()
var form_data;
var psw_vaule = [];
Page({
data: {
tempFilePaths: [],
img_arr: [],
},
//上传图片到服务器
formSubmit: function (e) {
var images_list = []; //设置了一个空数组进行储存服务器端图片路径
var that = this
var adds = that.data.img_arr;
for (var i = 0; i < this.data.img_arr.length; i++) {
wx.uploadFile({
url: 'https://www.bcxxjl.com/bcxxjl/tpwz/tupian.do', //填写实际接口
filePath: that.data.img_arr[i],
method:'POST',
name: 'file',
header: {
'content-type': 'multipart/form-data'
}, // 设置请求的 header
formData: adds,
success: function (res) {
var that = this
// json转换数组
var data1 = JSON.parse(res.data);
images_list.push(data1.src);//把每次返回的地址放入数组
if (3 == images_list.length) {
//var data = JSON.parse(res.data);
//console.log(data); //接口返回网络路径
//that.setData({imgsrc:data.src})
wx.request({
url: 'https://www.bcxxjl.com/bcxxjl/wztp/wenzi.do',
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST",
data: { biaoti: e.detail.value.biaoti, neirong: e.detail.value.neirong, zuozhe: e.detail.value.zuozhe, fenlei: e.detail.value.fenlei,
lianjie: e.detail.value.lianjie,
beizhu: e.detail.value.beizhu,
shunxu: e.detail.value.shunxu,
// img: that.data.imgsrc
img: images_list[1]
},
success: function (res) {
console.log(res.data);
if (res.data.status == 0) {
wx.showToast({
title: '提交失败!!!',
icon: 'loading',
duration: 1500
})
} else {
wx.showToast({
title: '提交成功!!!',//这里打印出登录成功
icon: 'success',
duration: 1000
})
}
}
})
}
}
})
}
this.setData({
formdata: ''
})
},
//从本地获取照片
upimg: function () {
var that = this;
if (this.data.img_arr.length < 3) {
wx.chooseImage({
count: 1, //一次性上传到小程序的数量
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
const tempFilePaths = res.tempFilePaths
console.log(res.tempFilePaths)
that.setData({
img_arr: that.data.img_arr.concat(res.tempFilePaths),
})
}
})
} else {
wx.showToast({
title: '最多上传三张图片',
icon: 'loading',
duration: 2000
})
}
},
//删除照片功能与预览照片功能
deleteImg: function (e) {
var that = this;
var img_arr = that.data.img_arr;
var index = e.currentTarget.dataset.index;
wx.showModal({
title: '提示',
content: '确定要删除此图片吗?',
success: function (res) {
if (res.confirm) {
console.log('点击确定了');
img_arr.splice(index, 1);
} else if (res.cancel) {
console.log('点击取消了');
return false;
}
that.setData({
img_arr: img_arr
});
}
})
},
previewImg: function (e) {
var index = e.currentTarget.dataset.index;
var img_arr = this.data.img_arr;
wx.previewImage({
current: img_arr[index],
urls: img_arr
})
},
})
小程序端wxss文件如下:
/**index.wxss**/
/* pages/productReleased/productReleased.wxss */
page {
background-color: #f1f1f1;
}
.title {
margin-top: 5rpx;
background-color: white;
width: 100%;
height: 80rpx;
}
.title_text {
margin-left: 20rpx;
width: 100%;
height: 50rpx;
padding-top: 10rpx;
display: flex;
}
.title_text text {
font-size: 30rpx;
}
.title_text input {
font-size: 30rpx;
width: 60vw;
margin-left: 20rpx;
}
.textarea {
height: 100rpx;
font-size: 30rpx;
margin-left: 40rpx;
width: 500rpx;
}
.info-point {
background-color: white;
width: 100%;
height: 100rpx;
margin-top: 5rpx;
}
/*选择图片View*/
.addImv {
background-color: white;
/* border: 1px dashed gray; */
display: flex;
flex-wrap: wrap;
align-items: center;
margin-top: 5rpx;
}
.upImv {
background-color: white;
width: 100%;
margin-top: 5rpx;
}
.upImv_text {
font-size: 30rpx;
margin-left: 20rpx;
padding-top: 20rpx;
}
/*添加图片*/
.addImv .chooseView {
width: 180rpx;
height: 180rpx;
margin: 20rpx 20rpx;
background-color: #f2f6f9;
border: 1px dashed lightgray;
text-align: center;
line-height: 180rpx;
/* padding: 0rpx 7rpx; */
border-radius: 5px;
margin-left: 40rpx;
}
.addImv .chooseImv {
width: 50rpx;
height: 50rpx;
}
/*已选择的图片*/
.addImv .upFile {
width: 180rpx;
height: 180rpx;
position: relative;
padding: 0rpx 7rpx;
margin-left: 40rpx;
border: 1px solid #c0ccda;
}
.addImv .upFile .itemImv {
width: 180rpx;
height: 180rpx;
padding: 0rpx 7rpx;
}
.addImv .upFile .closeImv {
position: absolute;
right: 0rpx;
top: 0rpx;
width: 50rpx;
height: 50rpx;
}
.logoinfo {
height: 128rpx;
width: 128rpx;
margin: 10rpx 10rpx 10rpx 10rpx;
}
.sureRelease {
background-color: #e44178;
color: white;
position: fixed;
width: 100%;
bottom: 0rpx;
}
.icon {
margin-left: 80rpx;
}
.tu {
border: 3rpx solid rgba(0, 0, 0, 0.329);
border-radius: 10rpx;
height: 60rpx; width: 60rpx;
margin: 20rpx 20rpx 20rpx 30rpx;
padding: 60rpx 60rpx 60rpx 60rpx;
}
.logoinfo {
height: 220rpx;
width: 220rpx;
margin: 10rpx 10rpx 10rpx 10rpx;
}
.tu1 {
display: flex;
flex-flow: row wrap;
align-content: space-around;
}
.an {
height: 90rpx;
width: 270rpx;
font-size: 38rpx;
background-color: rgba(0, 0, 0, 0.288);
font-weight: 600;
color: white;
}
button::after {
border: none;
}
.an1 {
margin-top: 90rpx;
}
服务器端接收图片的代码:文件名tpwztpController
package com.cn.controller;
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.sun.istack.internal.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
/**
* 图片上传代码
* @author a云淡风轻
* @createtime 2022年3月7日
*/
@Controller
@RequestMapping("/tpwz")
public class tpwztpController {
// private Logger logger = Logger.getLogger(TupianjieshouController.class);
/**
* @createtime 2022年3月7日
* @param request
* @param content
* @return
* @throws IOException
*/
@RequestMapping("/tupian.do")
@ResponseBody
public Object upload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
System.out.println("执行upload");
request.setCharacterEncoding("UTF-8");
HashMap s = new HashMap();
System.out.println("78910");
if(!file.isEmpty()) {
String path = null;
String type = null;
// 获取文件名
String fileName = file.getOriginalFilename();
System.out.println("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传的后缀名为:" + suffixName);
// 文件上传后的路径
String filePath = "/usr/upload/";
String temp_str="";
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
temp_str=sdf.format(dt);
UUID uuid = UUID.randomUUID();
File base = new File(filePath);
if (! base.exists()) {
base.mkdirs();
}
try {
file.transferTo(new File(filePath +uuid.toString() + temp_str+suffixName));
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int i;
i=0;
s.put("aaa", i);
s.put("src", uuid.toString() + temp_str+suffixName);
}
return s;
}
}
服务器端接收表单的代码:
```css
package com.cn.controller;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/wztp") //相似于命名空间,唯一标识一个Controller,防止名称重复
public class tpwzwzController {
Connection dbconn;
/**
* desc 返回字符串含义,指的是ModelAndView中的ViewName,也就是要跳转的页面
*
* @RequestMapping 请求的映射 映射到一个具体的方法 同value来指定,如果不写value也是默认给value赋值
* @throws IOException
*/
@RequestMapping("/wenzi.do")
public void addUserByHttpServletRequest(HttpServletRequest request) throws IOException{
String dburl = "jdbc:mysql://localhost:3306/******";//数据库名称换成你的
String username ="root";
String password = "******";//换成你的
try{
Class.forName("com.mysql.cj.jdbc.Driver");
dbconn = DriverManager.getConnection(dburl,username,password);
System.out.println("数据库连接成功");
}catch (ClassNotFoundException e1){
System.out.println(e1+"驱动程序找不到");
}catch(SQLException e2){
System.out.println(e2);
}
String biaoti1 = new String(request.getParameter("biaoti").getBytes("iso-8859-1"), "utf-8");
String neirong1 = new String(request.getParameter("neirong").getBytes("iso-8859-1"), "utf-8");
String zuozhe1 = new String(request.getParameter("zuozhe").getBytes("iso-8859-1"), "utf-8");
String fenlei1 = new String(request.getParameter("fenlei").getBytes("iso-8859-1"), "utf-8");
String lianjie1 = new String(request.getParameter("lianjie").getBytes("iso-8859-1"), "utf-8");
String beizhu1 = new String(request.getParameter("beizhu").getBytes("iso-8859-1"), "utf-8");
String shunxu1 = new String(request.getParameter("shunxu").getBytes("iso-8859-1"), "utf-8");
String beizhu2 = new String(request.getParameter("img").getBytes("iso-8859-1"), "utf-8");
String beizhu3="https://www.bcxxjl.com/tupian/";
String beizhu4=beizhu3+beizhu2;
Statement stmt;
int rs = 0;
String sql="insert into wenzhang (wenzhangbt,wenzhangneirong,wenzhangzuozhe,wenzhangfenlei,wenzhanglianjie,wenzhangbeizhu,fbsj,sxid) values ('"+biaoti1+"','"+neirong1+"','"+zuozhe1+"','"+fenlei1+"','"+lianjie1+"','"+beizhu4+"',now(),"+shunxu1+")";
try {
stmt = dbconn.createStatement();
rs = stmt.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("hello springmvc with annotation!");
System.out.println(biaoti1);
}
}
在这里插入代码片
存储的图片路径我在代码中已经拼接成浏览器可直接访问的路径。上面的演示代码中,我只保存了一张图片的路径,根据以上代码,读者很容易保存三张图片的路径。
下一篇,小程序从服务器读取数据显示图片和文字。