springboot+微信小程序实现文件上传下载(预览)pdf文件

实现思路:

  1. 选择文件 wx.chooseMessageFile ,官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseMessageFile.html
  2. 上传文件 `wx,uploadFile` , 官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html
  3. 查看所有上传的pdf文件,显示在页面上
  4. 点击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 设置上传文件的大小

spring:
  servlet:
    multipart:
      max-file-size: 5MB # 单个文件大小
      max-request-size: 50MB # 总文件大小Apache Commons FIle Upload

1.3 编写代码

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";
    }

}

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一种轻量级的 Java 应用程序框架,具有在微服务和云原生应用程序中构建可扩展和高效的应用程序的能力。而微信小程序是一种流行的移动应用程序,具有快速和轻量级的特点。在实际开发中,使用 Spring Boot微信小程序的结合是非常有意义的。其中,文件上传下载功能是常用的功能之一。 在 Spring Boot实现微信小程序文件上传下载功能一般需要采用 RESTful 接口实现。具体来说,可以使用 Spring Boot 中的控制器(Controller)和服务(Service)来实现。在前端,可以使用微信小程序的 API 调用上传下载文件。 对于文件上传功能,可以使用 Spring Boot 中的 MultipartFile 类来获取上传文件,并进行相关处理。具体的流程如下: 1. 在 Controller 中定义一个上传文件的接口,并指定请求方式、参数等信息。 2. 在 Service 中编写上传文件的逻辑代码,包括文件保存、处理、数据库操作等。 3. 在前端使用微信小程序的 API 调用上传文件功能,并将文件数据发送到后台指定的接口。 对于文件下载功能,一般需要在后台将文件保存在服务器上,并返回文件的链接或数据给前端。具体的流程如下: 1. 在 Controller 中定义一个下载文件的接口,并指定请求方式、参数等信息。 2. 在 Service 中编写下载文件的逻辑代码,包括读取文件、压缩文件、加密文件等。 3. 在前端使用微信小程序的 API 调用下载文件功能,并将文件链接或数据接收并处理。 上述步骤可以参考 Spring Boot微信小程序的文档和示例实现。需要注意的是,文件上传下载功能的具体实现可能会因不同的业务需求而有所差异。因此,在实际开发中需要根据具体情况灵活调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值