微信小程序之上传图片到Java Web服务器
目录
1.背景
2.微信小程序部署界面
3. Java Web后台实现
4. 微信小程序&Java Web后台建立连接
5. 运行思路整理
1.背景
话说课设来了,还是在期末。嗯嗯嗯额~这就很难受,还好最后顺利完成任务,并对微信小程序上传图片到web服务器有点理解。综上:此篇博客诞生了?
2.微信小程序部署界面
- 先看看小程序的目录结构
• 完善pages下的微信界面
index.wxml
<!--index.wxml-->
<text>单张或多张图片上传</text>
<view wx:for="{{perImgSrc}}" wx:key="ind" wx:for-item="item">
<view>{{ind}}</view>
<image src="http://localhost:8080/demo/{{item.src}}"></image>
</view>
<button bindtap="chooseImg">选择图片</button>
index.js
//index.js
//获取应用实例
const app = getApp()
var total = [];
Page({
data: {
perImgSrc: []
},
onLoad: function (options) {
// 页面初始化 options为页面跳转所带来的参数
},
onReady: function () {
// 页面渲染完成
},
onShow: function () {
// 页面显示
},
onHide: function () {
// 页面隐藏
},
onUnload: function () {
// 页面关闭
},
chooseImg: function () {
var that = this;
wx.chooseImage({
count: 9, // 默认9
sizeType: ['original'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
console.info(res.tempFilePaths.length);
that.uploadFile2(tempFilePaths, 0);
}
})
}, uploadFile: function (file, i) {//测试,没有什么屌用
var that = this;
wx.uploadFile({
url: 'http://localhost:8080/demo/upload', //仅为示例,非真实的接口地址
filePath: file,
name: 'file',
success: function (res) {
var obj = new Object();
obj.ind = i + 1;
var data = res.data;
console.info(data);
obj.src = data;
console.info("---------------------------------");
console.info(obj);
that.data.perImgSrc.push(obj);
}
})
}, uploadFile2: function (file, i) {//递归调用
var that = this;
wx.uploadFile({
url: 'http://localhost:8080/demo/upload', //仅为示例,非真实的接口地址
filePath: file[i],
name: 'file',
success: function (res) {
var obj = new Object();
obj.ind = i + 1;
var data = res.data;
console.info(data);
obj.src = data;
console.info("---------------------------------");
console.info(obj);
if (!((i + 1) == file.length)) {
total.push(obj);
that.uploadFile2(file, i + 1);
} else {
total.push(obj);
that.setData({ perImgSrc: total });
}
}
})
}
})
3. Java Web后台实现
• 创建web项目,编写UploadServlet.java文件
public class UploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); //设置编码
//获得磁盘文件条目工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
String str = request.getSession().getServletContext().getRealPath("");
//获取文件需要上传到的路径
String path = request.getRealPath("/upload");
System.out.println(path);
//String path =request.getSession().getServletContext().getRealPath("/upload");
System.out.println(path);
String pathStr=null;
System.err.println("上传的图片路径:"+path);
//如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
//设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
/**
* 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上,
* 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的
* 然后再将其真正写到 对应目录的硬盘上
*/
factory.setRepository(new File(path));
//设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
factory.setSizeThreshold(1024*1024);
//高水平的API文件上传处理
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//可以上传多个文件
List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
for(FileItem item : list){
//获取表单的属性名字
String name = item.getFieldName();
//如果获取的 表单信息是普通的 文本 信息
if(item.isFormField()){
//获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
String value = item.getString() ;
request.setAttribute(name, value);
}else {
/**
* 以下三步,主要获取 上传文件的名字
*/
//获取路径名
String value = item.getName() ;
//索引到最后一个反斜杠
//int start = value.lastIndexOf("");
//截取 上传文件的 字符串名字,加1是 去掉反斜杠,
String filename = value;
request.setAttribute(name, filename);
//真正写到磁盘上
//它抛出的异常 用exception 捕捉
//item.write( new File(path,filename) );//第三方提供的
//手动写的
str+="upload\\"+filename;
pathStr="/upload/"+filename;
System.err.println("文件存储的路径:"+str);
File file=new File(str);
OutputStream out = new FileOutputStream(file);
InputStream in = item.getInputStream() ;
int length = 0 ;
byte [] buf = new byte[1024] ;
System.out.println("获取上传文件的总共的容量:"+item.getSize());
// in.read(buf) 每次读到的数据存放在 buf 数组中
while( (length = in.read(buf) ) != -1){
//在 buf 数组中 取出数据 写到 (输出流)磁盘上
out.write(buf, 0, length);
}
in.close();
out.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
catch (Exception e) {
}
PrintWriter printWriter=response.getWriter();
// printWriter.print("{"path":""+pathStr+""}");
printWriter.print(pathStr);
printWriter.flush();
printWriter.close();
}
}
注:需要引入这样两个jar包commons-io-2.5.jar、commons-fileupload-1.3.2.jar;可在https://commons.apache.org下载。
• 更改web.xml配置文件
- 测试后台是否正常运行
注:请以Debug模式启动后台tomcat server,如果出现request contain null错误属正常情况。
4. 微信小程序&Java Web后台建立连接
index.wxml文件
index.js文件
- 点击选择图片,观察是否跳转至Java Web后台
注意:如果出现https证书问题,这是微信小程序默认设置无法读取本机url,更改一下配置即可
- 如果以上所有问题都以解决,基本上就已经成功了,这里提供微信小程序端窗口输出和界面显示截图
- 最后看看Java Web后台,可以发现在控制台输出的指定路径下有刚刚上传的图片了
5. 运行思路整理
- 微信小程序端点击选择图片
- 从index.wxml跳转到index.js中的chooseImg函数中
- 在chooseImg函数中又调用uploadFile2函数,并将选择的图片文件打包给uploadFile2
- uploadFile2中利用wx内部封装的uploadFile函数向指定url请求上传
- 跳转至Java Web后台,首先经过web.xml过滤跳转至UploadServlet.java执行对应方法实现图片上传至指定文件路径
- 最后微信小程序中的index.wxml中的src读取到Java Web指定路径下的上传文件,也就显示到了微信小程序界面了