微信小程下载word文档Java后台实现

微信小程序下载文件

开发环境:微信开发者工具+eclipse+Tomcat+Mysql

1、过程描述

微信开发者工具提供接口,访问eclipse中的Java项目地址,在对应的Java项目中从磁盘读取指定word文档。
Java后台用jacob读word,先根据word文档生成一个html文档,再用文件流对html文档读取,保证读出来的格式与原文件一致。
(关于jacob方式读word环境配置请参考https://blog.csdn.net/m0_46594891/article/details/105655858

2、代码

前台

.wxml

<view class="table">
 <view class="tr bg-header">
  <view class="th">文档名</view>
  <view class="th">上传时间</view>
  <view class="th">点击查看</view>
  <view class="th">点击删除</view>
 </view>
 <block wx:for="{{listData}}" wx:key="key">
  <view class="tr bg-items">
   <view class="td">{{item.fileName}}</view>
   <view class="td">{{item.date}}</view>
   <view class="td" bindtap="downloadFile" id="{{item.fileName}}">点击查看</view>
   <view class="td" bindtap="deleteFile" id="{{item.fileName}}">点击删除</view>
  </view>
 </block>
</view>

.js

var filePath;
var account;
var name;
Page({
   onLoad: function (options) {
   var that=this;
   var account = wx.getStorageSync('account');
   wx.request({
     url: 'http://192.168.x.xxx:8080/GraduateDesign/Stu_seeUploadedFile',
     data: {
       account    
     },
     method: 'GET',
     header: {
       'content-type': 'application/json' // 默认值
     },
     success: function (res) {
       that.setData({
     listData:res.data
    })
     }
   })
 },
  
  downloadFile: function(e) {
  wx.showLoading({
   title:'加载中'
  })
  setTimeout(function(){
   wx.hideLoading()
  },2000)
   name=e.currentTarget.id;
    let type = e.currentTarget.dataset.type;
    let url = e.currentTarget.dataset.url;
   if(name.indexOf("开题报告")>-1){
  wx.downloadFile({
    url: 'http://192.168.x.xxx:8080/GraduateDesign/DownloadKtbg?filename='+name,      
   header: {},
    success: function(res) {
      var filePath = res.tempFilePath;
      console.log(filePath);    
      wx.openDocument({
        filePath: filePath,
        fileType: 'doc',
        success: function(res) {
          console.log('打开文档成功')
        },
        fail: function(res) {
          console.log(res);
        },
        complete: function(res) {
          console.log(res);
        }
      })
    },
    fail: function(res) {
      console.log('文件下载失败');
    },
    complete: function(res) {},
  })
 }
 else if(name.indexOf("任务书")>-1){
  wx.downloadFile({
    url: 'http://192.168.x.xxx:8080/GraduateDesign/DownloadRws?filename='+name,      
    header: {},
    success: function(res) {
      var filePath = res.tempFilePath;
      console.log(filePath);
      wx.openDocument({
        filePath: filePath,
        fileType: 'doc',
        success: function(res) {
          console.log('打开文档成功')
        },
        fail: function(res) {
          console.log(res);
        },
        complete: function(res) {
          console.log(res);
        }
      })
    },
    fail: function(res) {
      console.log('文件下载失败');
    },
    complete: function(res) {},
  })
 }
 else if(name.indexOf("论文")>-1){
  wx.downloadFile({
    url: 'http://192.168.x.xxx:8080/GraduateDesign/DownloadPaper?filename='+name,      
    header: {},
    success: function(res) {
      var filePath = res.tempFilePath;
      console.log(filePath);
      wx.openDocument({
        filePath: filePath,
        fileType: 'doc',
        success: function(res) {
          console.log('打开文档成功')
        },
        fail: function(res) {
          console.log(res);
        },
        complete: function(res) {
          console.log(res);
        }
      })
    },
    fail: function(res) {
      console.log('文件下载失败');
    },
    complete: function(res) {},
  })
 }
 else if(name.indexOf("选题")>-1){
  wx.downloadFile({
    url: 'http://192.168.x.xxx:8080/GraduateDesign/DownloadTimu?filename='+name,      
    header: {},
    success: function(res) {
      var filePath = res.tempFilePath;
      console.log(filePath);
      wx.openDocument({
        filePath: filePath,
        fileType: 'doc',
        success: function(res) {
          console.log('打开文档成功')
        },
        fail: function(res) {
          console.log(res);
        },
        complete: function(res) {
          console.log(res);
        }
      })
    },
    fail: function(res) {
      console.log('文件下载失败');
    },
    complete: function(res) {},
  })
 }
 else{
  wx.showToast({
    title: '请删除该文件',
    duration: 2000,
  })
 }    
  },
 
 deleteFile:function(e){
  wx.showModal({
   title:'提示',
   content:'确定删除?',
   success: function (res) {
       if (res.confirm) {//这里是点击了确定以后
         var account = wx.getStorageSync('account');
         name=e.currentTarget.id;
         wx.request({
           url: 'http://192.168.x.xxx:8080/GraduateDesign/Stu_DeleteFile',
           data: {
             account,
           name
           },
           method: 'GET',
           header: {
             'content-type': 'application/json' // 默认值
           },
           success(res) {
             if(res.data==1){
            wx.showToast({
              title: '删除成功',
            })     
           }      
             else{
               wx.showToast({
                 title: '删除失败',
               })
             }
           }
          })
          this.onLoad()
       } else {//这里是点击了取消以后
         console.log('用户点击取消')
       }
     }
  })
 } 
})

.json

{
  "navigationBarTitleText": "已上传文件"
}

.wxss

.table {
    border: 0px solid darkgray;
    font-size: 12px;
  }
  .tr {
    display: flex;
    width: 100%;
    justify-content: center;
    height: 2rem;
    align-items: center;
  }
  .td {
      width:100%;
      justify-content: center;
      text-align: center;
  }
  .bg-header{
    background: snow;
  }
  
  .th {
    width: 100%;
    justify-content: center;
    background: rgba(3, 156, 54, 0.973);
    color: #fff;
    display: flex;
    height: 2rem;
    align-items: center;
  }
后台

注:我的前台根据自己的需求写了几个不同的接口,在这里后台只列出其中一个,其他的都是类似的。

下载论文接口DownloadPaper实现

package GraduateDesign.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class DownloadPaper extends HttpServlet {
 private static final long serialVersionUID = 1L;
 public DownloadPaper() {
        super();
        // TODO Auto-generated constructor stub
    }
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  request.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  response.setHeader("Access-Control-Allow-Origin", "*"); 
  response.setHeader("Access-Control-Allow-Methods", "GET,POST");
  
  String filename=request.getParameter("filename");//微信小程序url中传过来的参数
  String DocFile = "D:\\eclipse-workspace\\GraduateDesign\\WebContent\\WEB-INF\\paper\\"+filename;
  String HtmlFile = DocFile.substring(0, (DocFile.length() - 4)) + ".html";
  ActiveXComponent app = new ActiveXComponent("Word.Application");
  try{
   app.setProperty("Visible", new Variant(false));
      //设置word程序非可视化运行
   Dispatch docs = app.getProperty("Documents").toDispatch();
   Dispatch doc = Dispatch.invoke(docs,"Open", Dispatch.Method, new Object[]{DocFile,new Variant(false), new Variant(true)}, new int[1]).toDispatch(); 
      //打开word文件
   Dispatch.invoke(doc,"SaveAs",Dispatch.Method, new Object[]{HtmlFile,new Variant(8)}, new int[1]);
            //作为html格式保存文件
   Dispatch.call(doc, "Close",new Variant(false));
            //关闭文件
      }
   catch (Exception e)
   {
         e.printStackTrace();
   }
   finally
   {
      app.invoke("Quit", new Variant[] {});
   //退出word程序
   }
   //转化完毕

   response.setContentType("multipart/form-data");
   response.setCharacterEncoding("UTF-8");
   response.setContentType("text/html");
   // 2.设置文件头:最后一个参数是设置下载文件名
   response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
   ServletOutputStream out;
   // 通过文件路径获得File对象
   HtmlFile = HtmlFile.replace("\\", "/");
   File html_file = new File(HtmlFile);
   FileInputStream inputStream = new FileInputStream(html_file);
   // 3.通过response获取ServletOutputStream对象(out)
   out = response.getOutputStream();
   int b = 0;
   byte[] buffer = new byte[1024];
   while ((b = inputStream.read(buffer)) != -1) {
   // 4.写到输出流(out)中
       out.write(buffer, 0, b);
   }
   inputStream.close();
   out.flush();
   out.close();
   Writer out1 = response.getWriter();
   out1.write(b);
   out1.flush();
 }

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     doGet(request, response);
   }
}

3、运行结果

查看文件必须要用真机调试,不能在微信开发者工具中预览。

在这里插入图片描述

点击查看
在这里插入图片描述
要等一会才能显示出来
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值