最近在做小程序多图片上传到Java后台,Java后台是用springboot写的。也算是踩了不少坑,今天就来带大家来一步步实现小程序端多图片的上传。
小程序端上传成功的回调
Java端接受到图片后的打印
链接可以直接在浏览器里打开查看
其实这两个截图就可以看出,我们图片上传成功了,并且给小程序前端返回了可供访问的图片url。
话不多说,直接看代码。
1,wxml布局文件
其实页面很简答,一个上传按钮,一个选择图片按钮。一定要记得先选择图片,然后再点击图片上传。
2,js文件
再来看下js文件,js文件里最重要的就是uploadFile方法
uploadFile方法里我们请求自己的Java后台接口,进行图片上传。这里有些注意点要给大家说下
Page({
data: {
img_arr: [],
formdata: '',
},
//点击发布按钮
formSubmit() {
this.uploadFile(0)
},
//上传图片
uploadFile: function (index) {
var that = this
//如果所有图片都已经上传完,就不再往下执行
if (index >= that.data.img_arr.length) {
return
}
wx.uploadFile({
url: 'http://localhost:8080/upload/picture', //自己的Java后台接口地址
filePath: that.data.img_arr[index],
name: 'content',
header: {
"Content-Type": "multipart/form-data",
'accept': 'application/json',
'Authorization': 'okgoodit' //若有token,此处换上你的token,没有的话省略
},
formData: ({ //上传图片所要携带的参数
username: "编程小石头",
password: '2501902696'
}),
success: function (res) {
console.log(`第${index+1}张上传成功`, res)
index++
that.uploadFile(index)
},
fail(res) {
console.log(`第${index+1}张上传失败`, res)
}
})
},
//选择要上传的图片
upimg: function () {
var that = this;
//这里小程序规定最好只能选9张,我这里随便填的3,你也可以自己改
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后台的实现。
先来看后台代码目录,后台代码很简单,就是一个UploadController
这里的主要实现方法都在uploadPicture
@RequestMapping("/picture")
public String uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
String filePath = "";
request.setCharacterEncoding("utf-8"); //设置编码
String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
File dir = new File(realPath);
//文件目录不存在,就创建一个
if (!dir.isDirectory()) {
dir.mkdirs();
}
try {
StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
//获取formdata的值
Iterator 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 fileName = file.getOriginalFilename();
//真正写到磁盘上
String uuid = UUID.randomUUID().toString().replace("-", "");
String kzm = fileName.substring(fileName.lastIndexOf("."));
String filename = uuid + kzm;
File file1 = new File(realPath + filename);
OutputStream out = new FileOutputStream(file1);
out.write(file.getBytes());
out.close();
filePath = request.getScheme() + "://" +
request.getServerName() + ":"
+ request.getServerPort()
+ "/uploadFile/" + filename;
System.out.println("访问图片路径:" + filePath + "====username:" + username);
}
} catch (Exception e) {
logger.error("", e);
}
return filePath;
}
这里我给大家讲下实现步骤
package com.img.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.util.Iterator;
import java.util.UUID;
/**
* 图片上传
* 编程小石头
*/
@RestController
@RequestMapping("/upload")
public class UploadController {
private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
@RequestMapping("/picture")
public String uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
String filePath = "";
request.setCharacterEncoding("utf-8"); //设置编码
String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
File dir = new File(realPath);
//文件目录不存在,就创建一个
if (!dir.isDirectory()) {
dir.mkdirs();
}
try {
StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
//获取formdata的值
Iterator 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 fileName = file.getOriginalFilename();
//真正写到磁盘上
String uuid = UUID.randomUUID().toString().replace("-", "");
String kzm = fileName.substring(fileName.lastIndexOf("."));
String filename = uuid + kzm;
File file1 = new File(realPath + filename);
OutputStream out = new FileOutputStream(file1);
out.write(file.getBytes());
out.close();
filePath = request.getScheme() + "://" +
request.getServerName() + ":"
+ request.getServerPort()
+ "/uploadFile/" + filename;
System.out.println("访问图片路径:" + filePath + "====username:" + username);
}
} catch (Exception e) {
logger.error("", e);
}
return filePath;
}
}
至于如何创建springboot项目这么基础的知识,我这里就不再给大家讲解了。