zoukankan      html  css  js  c++  java
  • c# 预览服务器文件

    后台

    using Aspose.Cells;
    using Aspose.Slides.Pptx;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Text;
    using System.Web.Http;

    namespace DocOnlineView.UI.Controllers.MVCAPI
    {
    public class HomeController : ApiController
    {
    [HttpGet]
    public DataTable CourseViewOnLine(string sourceDoc, string fileName)
    {
    DataTable dtlist = new DataTable();
    dtlist.Columns.Add("TempDocHtml", typeof(string));

    string fileDire = "/Files";
    //string sourceDoc = Path.Combine(fileDire, fileName);
    string saveDoc = "";

    string docExtendName = System.IO.Path.GetExtension(sourceDoc).ToLower();
    if (docExtendName == ".jpg" || docExtendName == ".png" || docExtendName == ".bmp" || docExtendName == ".gif")
    {
    string path = System.Web.HttpContext.Current.Server.MapPath("文档" + docExtendName + "");
    downFile(sourceDoc);
    string p = path;
    int cou = path.Substring(0, path.IndexOf("DocOnlineView.UI")).Length;
    p = p.Substring(cou + 16, p.Length - cou - 16);
    p = p.Replace("\", "/");
    //DataRow dr = new DataRow();
    //dr["TempDocHtml"] = p;
    dtlist.Rows.Add(p);
    }
    else
    {
    bool result = false;
    if (docExtendName == ".pdf")
    {
    //pdf模板文件
    string tempFile = Path.Combine(fileDire, "temppdf.html");
    saveDoc = Path.Combine(fileDire, "viewFiles/onlinepdf.html");
    result = PdfToHtml(
    sourceDoc,
    System.Web.HttpContext.Current.Server.MapPath(tempFile),
    System.Web.HttpContext.Current.Server.MapPath(saveDoc), fileName);
    }
    else if (docExtendName == ".txt")
    {
    //txt模板文件
    string tempFile = Path.Combine(fileDire, "temptxt.html");
    saveDoc = Path.Combine(fileDire, "viewFiles/onlinetxt.html");
    result = PdfToHtmlTXT(
    sourceDoc,
    System.Web.HttpContext.Current.Server.MapPath(tempFile),
    System.Web.HttpContext.Current.Server.MapPath(saveDoc), fileName);
    }
    else
    {
    saveDoc = Path.Combine(fileDire, "viewFiles/onlineview.html");
    result = OfficeDocumentToHtml(
    sourceDoc,
    System.Web.HttpContext.Current.Server.MapPath(saveDoc));
    }

    if (result)
    {
    dtlist.Rows.Add(saveDoc);
    }
    }

    return dtlist;
    }

    //方法
    long totalDownloadedByte = 0;
    long logbyte = 0;
    private bool OfficeDocumentToHtml(string sourceDoc, string saveDoc)
    {
    bool result = false;
    //获取文件扩展名
    string docExtendName = System.IO.Path.GetExtension(sourceDoc).ToLower();
    string path = System.Web.HttpContext.Current.Server.MapPath("文档" + docExtendName + "");
    downFile(sourceDoc);
    switch (docExtendName)
    {
    case ".doc":
    case ".docx":
    Aspose.Words.Document doc = new Aspose.Words.Document(path);
    doc.Save(saveDoc, Aspose.Words.SaveFormat.Html);
    result = true;
    break;
    case ".xls":
    case ".xlsx":
    Workbook workbook = new Workbook(path);
    workbook.Save(saveDoc, SaveFormat.Html);

    result = true;
    break;
    case ".ppt":
    case ".pptx":
    PresentationEx pres = new PresentationEx(path);
    pres.Save(saveDoc, Aspose.Slides.Export.SaveFormat.Html);
    result = true;
    break;
    default:
    break;
    }
    System.IO.File.Delete(path);
    return result;
    }

    /// <summary>
    /// txt预览
    /// </summary>
    /// <param name="sourceDoc"></param>
    /// <param name="tempFile"></param>
    /// <param name="saveDoc"></param>
    /// <param name="fileName"></param>
    /// <returns></returns>
    private bool PdfToHtmlTXT(string sourceDoc, string tempFile, string saveDoc, string fileName)
    {
    //获取文件扩展名
    string docExtendName = System.IO.Path.GetExtension(sourceDoc).ToLower();
    string path = System.Web.HttpContext.Current.Server.MapPath("文档" + docExtendName + "");
    downFile(sourceDoc);
    byte[] b = new byte[1024 * 1024];
    FileStream fileRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
    int r = fileRead.Read(b, 0, b.Length);
    string contents = Encoding.Default.GetString(b, 0, r);

    //---------------------读html模板页面到stringbuilder对象里----
    StringBuilder htmltext = new StringBuilder();
    using (StreamReader sr = new StreamReader(tempFile)) //模板页路径
    {
    String line;
    while ((line = sr.ReadLine()) != null)
    {
    htmltext.Append(line);
    }
    sr.Close();
    sr.Dispose();
    }
    fileRead.Close();
    fileRead.Dispose();
    path = path.Replace("\", "/");
    //----------替换htm里的标记为你想加的内容
    htmltext.Replace("$PDFFILEPATH", contents);

    //----------生成htm文件------------------――
    using (StreamWriter sw = new StreamWriter(saveDoc, false,
    System.Text.Encoding.GetEncoding("utf-8"))) //保存地址
    {
    sw.WriteLine(htmltext);
    sw.Flush();
    sw.Close();
    sw.Dispose();

    }
    System.IO.File.Delete(path);
    return true;
    }
    /// <summary>
    /// 文件下载
    /// </summary>
    /// <param name="sourceDoc"></param>
    public void downFile(string sourceDoc)
    {
    //获取文件扩展名
    string docExtendName = System.IO.Path.GetExtension(sourceDoc).ToLower();
    string log = "";
    System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(sourceDoc);
    System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
    long totalBytes = myrp.ContentLength;
    System.IO.Stream st = myrp.GetResponseStream();
    string path = System.Web.HttpContext.Current.Server.MapPath("文档" + docExtendName + "");
    System.IO.Stream so = new System.IO.FileStream(path, System.IO.FileMode.Create);
    totalDownloadedByte = 0;
    byte[] by = new byte[1024];
    int osize = st.Read(by, 0, (int)by.Length);
    DateTime dt1 = DateTime.Now;
    int k = 0;
    while (osize > 0)
    {
    if (k > 10)
    {
    totalDownloadedByte = 0;
    logbyte = 0;

    break;
    }
    DateTime dt2 = DateTime.Now;
    if ((dt2 - dt1).Seconds > 1)
    {
    dt1 = dt2;
    log += "下载速度" + ((totalDownloadedByte - logbyte) / 1024).ToString("0") + "KB ";
    logbyte = totalDownloadedByte;
    k++;
    }
    totalDownloadedByte = osize + totalDownloadedByte;
    so.Write(by, 0, osize);
    osize = st.Read(by, 0, (int)by.Length);
    }
    so.Close();
    so.Dispose();
    st.Close();
    st.Dispose();
    }

    private bool PdfToHtml(string sourceDoc, string tempFile, string saveDoc, string fileName)
    {
    //获取文件扩展名
    string docExtendName = System.IO.Path.GetExtension(sourceDoc).ToLower();
    string path = System.Web.HttpContext.Current.Server.MapPath("文档" + docExtendName + "");
    downFile(sourceDoc);
    //---------------------读html模板页面到stringbuilder对象里----
    StringBuilder htmltext = new StringBuilder();
    using (StreamReader sr = new StreamReader(tempFile)) //模板页路径
    {
    String line;
    while ((line = sr.ReadLine()) != null)
    {
    htmltext.Append(line);
    }
    sr.Close();
    sr.Dispose();
    }
    string p = path;
    int cou = path.Substring(0, path.IndexOf("DocOnlineView.UI")).Length;
    p = p.Substring(cou + 16, p.Length - cou - 16);
    p = p.Replace("\", "/");
    //----------替换htm里的标记为你想加的内容
    htmltext.Replace("$PDFFILEPATH", p);

    //----------生成htm文件------------------――
    using (StreamWriter sw = new StreamWriter(saveDoc, false,
    System.Text.Encoding.GetEncoding("utf-8"))) //保存地址
    {
    sw.WriteLine(htmltext);
    sw.Flush();
    sw.Close();
    sw.Dispose();

    }
    //System.IO.File.Delete(path);
    return true;
    }
    }
    }

    前台使用弹窗

    //在线预览开始

    <script src="~/js/pdfobject/pdfobject.js"></script>
    <script src="~/js/PopupDialog/jquery.easing.1.3.js"></script>
    <script src="~/js/zDialog/zDrag.js"></script>
    <script src="~/js/zDialog/zDialog.js"></script>


    $(function () {
    //SexyLightbox.initialize({ color: 'white' });
    });

    //sourceDoc:服务器路径 fileName:文件名称

    var viewDoc = function (sourceDoc,fileName) {
    showLoading("body", "正在生成预览");

    //生成html文件
    $.ajax({
    url: "api/Home/CourseViewOnLine?fileName=" + fileName + "&sourceDoc=" + sourceDoc,
    type: "GET",
    dataType: "json",
    success: function (data) {
    closeLoading();

    //alert(JSON.stringify(data));
    var diag = new Dialog();
    diag.Width = 900;
    diag.Height = 400;
    diag.Title = "内容页为外部连接的窗口";
    alert(data[0].TempDocHtml);
    diag.URL = "http://localhost:8640/" + data[0].TempDocHtml + "?ver=" + Math.random() * 10;
    diag.show();

    //$("#hidePopupDialog").attr('href', '' + data[0].TempDocHtml + '?TB_iframe=true&height=450&width=920');
    //$("#hidePopupDialog").click();
    },
    error: function () {
    closeLoading();
    alert('生成失败');
    }
    });
    }

    // 加载遮罩
    var showLoading = function (elementTag, message) {
    var msg = message ? message : "加载数据,请稍候...";
    $("<div class="datagrid-mask"></div>").css({
    display: "block", "100%",
    height: $(elementTag).height()
    }).appendTo(elementTag);
    $("<div class="datagrid-mask-msg"></div>")
    .html(msg)
    .appendTo(elementTag).css({ display: "block", left: "30%", top: ($(elementTag).height() - 45) / 2 });
    };

    //关闭遮罩
    var closeLoading = function () {
    $('.datagrid-mask').remove();
    $('.datagrid-mask-msg').remove();
    };

    //在线预览结束

    再三须慎意,第一莫欺心
  • 相关阅读:
    mount命令详解
    traceroute命令详解
    etcd节点扩容至两个节点
    shell历史命令
    etcd单节点安装
    linux中修改环境变量及生效方法
    ansible最佳实战部署nginx
    用roles部署nginx
    playbook部署mangodb
    安装mangodb
  • 原文地址:https://www.cnblogs.com/otsf/p/11543177.html
Copyright © 2011-2022 走看看