微信小程序与java后台的交互
目录
微信小程序与java后台的交互
说明
1-这篇文章主要给想知道java 后台与小程序交互学习用的
2-后端采用的时mongodb 作为一个服务器实现一个上传下载分页的 和预览图片的没有到mysql
3-gitee 前端的源码:
4-gitee java后端的源码:
5-下面介绍的是前端与后端几种请求方式
6-先给你们看下成果图
1-首先在微信小程序详情那里把https 打上勾
2-小程序分页的请求 前端
getInfo: function () {
var that = this;
wx.request({
url: 'http://localhost:8080/file/getPage',
data: { page: that.data.page, pageSize: that.data.pageSize},
success: function (res) {
var contentlistTem = that.data.contentlist;
if (res.statusCode == 200) {
//已有数据
var contentlist = res.data.content;
//总数量
var contTotal = res.data.totalElements;
//当前数据量
var contPage = that.data.pageSize;
//总数居 - 当前搜索的数据 成立
contentlistTem.length =0;
if(contTotal >= contPage){
that.setData({
contentlist: contentlistTem.concat(contentlist),
hasMoreData: true,
})
}else{
that.setData({
contentlist: contentlistTem.concat(contentlist),
hasMoreData:false,
})
}
}else{
wx.showToast({
title: '出现异常'
})
}
}
})
},
2-1 小程序后端接口分页
/**
* 查询多条数据 属于分级查询 limit 不指定就查询所有
* skip 表示跳过行数 不指定就跳过
*
* @param page
* @param pageSize
* @return
*/
@ResponseBody
@GetMapping("/getPage")
public PageImpl<files> getPage(int page, int pageSize) {
System.out.println("查询多条数据:属于分级查询");
//mongodb 构造器
Query query = new Query();
//每页五个
Pageable pageable= PageRequest.of(page,pageSize);
query.with(pageable);
//按sql排序
query.with( Sort.by(Sort.Direction.DESC,"metadDate"));
//mongodb 查询全部数据
Query queryCount = new Query();
//按sql排序
queryCount.with( Sort.by(Sort.Direction.DESC,"_id"));
//查询总数
Long count =mongoTemplate.count(queryCount,files.class);
List<files> r = mongoTemplate.find(query, files.class);
return (PageImpl<files>) PageableExecutionUtils.getPage(r,pageable,()->count);
}
3- 小程序上传图片的请求方式
loadimg: function () {
var _this = this;
console.log( _this.tempFiles);
wx.uploadFile({
url: 'http://localhost:8080/file/uploadFile', //接口
filePath: _this.data.usernameUrl,
name: 'file',
success: function (res) {
var data = res.data;
wx.showToast({
title: '操作成功!', // 标题
icon: 'success', // 图标类型,默认success
duration: 1500 // 提示窗停留时间,默认1500ms
})
},
fail: function (error) {
wx.showToast({
title: '操作失败!', // 标题
icon: 'success', // 图标类型,默认success
duration: 1500 // 提示窗停留时间,默认1500ms
})
console.log(error);
}
})
},
3-1 小程序java 后端的上传接口
/**
* 文件上传
*
* @param file
* @return
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public Object uploadFile(@RequestParam("file") MultipartFile file) throws IOException, ServletException {
//文件名称
String originalFilename = file.getOriginalFilename();
if (originalFilename == null) {
return "请上传文件";
}
//获得文件输入流
InputStream inputStream = file.getInputStream();
//获得文件类型
String contentType = file.getContentType();
//将文件存储到mongodb 中,mongodb将会返回这个文件得具体信息
ObjectId gridFSFile = gridFsTemplate.store(inputStream, originalFilename, contentType);
System.out.println(gridFSFile);
return gridFSFile.toString();
}
4- 小程序下载 图片和附件请求方式
wx.downloadFile({
url: "http://localhost:8080/file/download?objectid="+id+"",
success: function (res) {
let path = res.tempFilePath
const tempFilePath = res.tempFilePath;
// 保存文件
wx.saveFile({
tempFilePath,
tempFilePath: path,
success: function (res) {
// let path = res.tempFilePath
const savedFilePath = res.savedFilePath;
var app = getApp();
// 打开文件
wx.openDocument({
filePath: savedFilePath,
fileType: app.globalData.fileType,
success: function (res) {
console.log('打开文档成功')
},
fail:function(e) {
wx.showToast({
title: '下载完成!', // 标题
icon: 'success', // 图标类型,默认success
duration: 1600 // 提示窗停留时间,默认1500ms
})
// console.log("不是文件保存的地方在:C:\Users\Administrator\AppData\Local\微信开发者工具\User Data\87e84c5c2e6751b62ab5919b87cb90af\WeappSimulator\WeappFileSystem\o6zAJs7QEFfbQGfNI6hp48TRegmw\wx9ac1d45a027bafa1\store");
},
});
},
fail: function (err) {
console.log('保存失败:', err)
}
});
},
fail: function (err) {
console.log('下载失败:', err);
},
})
4-1 小程序下载和图片预览的服务接口
/**
* 文件下载 如果是图片可以直接通过<IMG SRC = '这个方法的访问路径加上文件的id'
* 下载直接 get 请求调用
* 回显 需要特殊方法
* 例如图片回显 <img src="http://127.0.0.1:8081/download?file=${ObjectId}"></img>
* 当中的ObjectId是文件对应的图片id 路径就是访问的本地下载的页面
*
* @return
*/
@RequestMapping("/download")
public void download(String objectid, HttpServletResponse response) throws IOException {
System.out.println("---------下传文件");
//根据id 查询数据
Query id = Query.query(Criteria.where("_id").is(objectid));
GridFSFile fsFiles = gridFsTemplate.findOne(id);
if (fsFiles == null) {
System.out.println("没用获取到文件");
}
//文件名称
String s = fsFiles.getFilename();
//文件类型
Document metadata = fsFiles.getMetadata();
if (metadata == null) {
System.out.println("\"获取文件为空\";");
}
String contentType = fsFiles.getMetadata().get("_contentType").toString();
System.out.println("文件类型:" + contentType);
//通知下载
response.setContentType(contentType);
response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(s, "UTF-8") + "\"");
//mongdb文件操作 因为他是分片存的
GridFSBucket gridFSBucket = GridFSBuckets.create(mongoTemplate.getDb());
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(fsFiles.getObjectId());
//获取mongodb的资源
GridFsResource gridFsResource = new GridFsResource(fsFiles, gridFSDownloadStream);
//文件输入流
InputStream inputStream = gridFsResource.getInputStream();
//文件输出流
ServletOutputStream outputStream = response.getOutputStream();
//拷贝流
IOUtils.copy(inputStream, outputStream);
//关流
outputStream.flush();
outputStream.close();
inputStream.close();
System.out.println("-------下载完成------------");
}