实现思路:
- 选择文件
wx.chooseMessageFile
,官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseMessageFile.html - 上传文件 `wx,uploadFile` , 官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html
- 查看所有上传的pdf文件,显示在页面上
- 点击pdf文件就实现预览
5.1 先下载 wx.downloadFile
官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/network/download/wx.downloadFile.html
5.2 在查看 wx.openDocument
官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/file/wx.openDocument.html
小程序端wxml
<!--pages/uploadPDF/uploadPDF.wxml-->
<view>
<view>
<button type="primary" bindtap="uploadPDF">上传pdf文档</button>
</view>
<view style="margin:20% auto;width: 100%;">
<button bindtap="loadPdfList">加载pdf文档</button>
<view style="border: 1px solid black;width: 100%;">
<view wx:if="{{pdfList.length>0}}">
<view wx:for="{{pdfList}}" style="margin:5px;display: flex;justify-content: center;align-items: center;">
<text style="text-overflow: ellipsis; word-wrap: break-word;width: 80%;">{{item}}</text>
<button size="mini" type="warn" data-src="{{item}}" bindtap="lookPDF">查看</button>
</view>
</view>
<view wx:else style="text-align: center;">
<text>暂无</text>
</view>
</view>
</view>
</view>
小程序端ts
/**
* 页面的初始数据
*/
data: {
//pdf文档
pdfList: {}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad() {
},
uploadPDF() {
console.log("uploadPDF")
wx.chooseMessageFile({
//最多可以选择的文件数量,最多是0-100
count: 1,
//指打开文件的类型
type: "file",
success: (res) => {
let path = res.tempFiles[0].path
let suffix = path.split(".")[1]
if (suffix != "pdf") {
console.log("只能上传pdf的文件")
return
}
wx.uploadFile({
url: "http://172.16.50.86:8080/upload",
header: {
"Content-Type": "multipart/form-data"
},
name: "file",
filePath: path,
success: (res) => {
if (res.statusCode == 200) {
console.log("上传成功")
} else {
console.error(res.data)
}
}
})
}
})
},
//加载pdf列表
loadPdfList() {
wx.request({
url: "http://172.16.50.86:8080/fileList",
method: "GET",
success: (res) => {
this.setData({
pdfList: res.data
})
}
})
},
//查看pdf文档
lookPDF(e) {
wx.showLoading({
title:"加载中...",
mask:true
})
let imgUrl = e.currentTarget.dataset.src
wx.downloadFile({
url: "http://172.16.50.86:8080/download?file=" + imgUrl,
success: (res) => {
if (res.statusCode === 200) {
setTimeout(() => {
wx.openDocument({
filePath:res.tempFilePath,
fileType:"pdf"
})
wx.showToast({
title:"加载成功!.",
icon:"success",
duration:2000,
})
wx.hideLoading()
}, 1500);
}
},fail(){
wx.hideLoading()
}
})
},
后端
1.1 导入相关的maven依赖
<!--文件上传与下载相关的依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
1.2 设置上传文件的大小文章来源:https://www.toymoban.com/news/detail-721450.html
spring:
servlet:
multipart:
max-file-size: 5MB # 单个文件大小
max-request-size: 50MB # 总文件大小Apache Commons FIle Upload
1.3 编写代码文章来源地址https://www.toymoban.com/news/detail-721450.html
package com.demo1.web;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
@RestController
public class UploadController {
/**
* 文件上传
*
* @param request
* @param file
* @return
* @throws IOException
*/
@PostMapping("/upload")
@CrossOrigin
public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
String parameter = request.getParameter("filePath");
System.out.println("parameter = " + parameter);
if (!file.isEmpty()) {
//上传文件路径
// String path = request.getServletContext().getRealPath("/uploadFiles/");
String path = "C:/upload";
//获得上传文件名
String fileName = file.getOriginalFilename();
File filePath = new File(path + File.separator + fileName);
System.out.println(filePath);
//如果文件目录不存在,创建目录
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件中
file.transferTo(filePath);
return fileName;
}
return "fail";
}
/**
* 文件下载
*
* @param request
* @param fileName
* @return
* @throws IOException
*/
@GetMapping("download")
@CrossOrigin
public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("file") String fileName) throws IOException {
//下载文件路径
String path = "C:/upload";
//构建将要下载的文件对象
File file = new File(path + File.separator + fileName);
//设置响应头
HttpHeaders headers = new HttpHeaders();
//下载显示的文件名,解决中文名称乱码问题
String downloadFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
//通知浏览器以下载方式(attachment)打开文件
headers.setContentDispositionFormData("attachment", downloadFileName);
//定义以二进制流数据(最常见的文件下载)的形式下载返回文件数据
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//使用spring mvc框架的ResponseEntity对象封装返回下载数据
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
}
@GetMapping("/fileList")
@CrossOrigin
public List<String> list(HttpServletRequest request) {
String path = "C:/upload";
File file = new File(path);
List<String> arrayList = new LinkedList<>();
for (String list : file.list()) {
String str = list;
String split = list.substring(list.indexOf(".") + 1);
if (split.equals("pdf")) {
arrayList.add(list);
}
}
return arrayList;
}
@GetMapping("/hello")
public String hello() {
return "hello";
}
}
到了这里,关于springboot+微信小程序实现文件上传下载(预览)pdf文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!