【问题标题】:C# Web Service Return PDF stored as BLOB to PDFC# Web 服务将存储为 BLOB 的 PDF 返回到 PDF
【发布时间】:2023-03-30 19:53:01
【问题描述】:

我是 C#(和 Visual Studio)的新手。到目前为止,我已经成功部署了一个从本地 MSSQL 服务器读取数据的 WEB 服务,但我想使用 VS2010 对其进行扩展。

我有一个本地 mySQL 数据库,其中除其他数据外,还有一个存储 PDF 文件的 BLOB 列。我想阅读此 BLOB 列并从 Web 服务以 PDF 文件的形式返回结果。该服务将从 PHP 调用,在类似情况下,我可以毫不费力地呈现 PDF。

到目前为止,通过谷歌搜索,我能够读取数据并将其存储为本地文件。我不想将数据存储在文件中,而是将其存储在变量中(哪种类型?),这样我就可以将此变量作为 Web 服务的回复发送。

谢谢!

(我有很强的 PHP 背景,但我发现将这个背景“翻译”到 VS 有一些困难)

【问题讨论】:

  • 您是如何实现 Web 服务的? ASP.NET? MVC?
  • WCF 服务应用程序。我只是将它复制到本地 IIS 并从 PHP 应用程序调用它。

标签: c# web-services pdf


【解决方案1】:

首先 - 为什么不是 VS2015?社区版是免费的并且支持扩展。没有理由活在过去:)

对于您的问题,我认为您只是缺少标题信息。

如果你把它作为 mime 类型添加到你的输出中,你应该可以回家了:

即:

var pdfBytes = DocumentRepository.GetPdfAsByteArray(myPdf);
context.Response.StatusCode = (int) HttpStatusCode.OK;
context.Response.ContentType = "application/pdf";
context.Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);

【讨论】:

  • 这听起来不错,谢谢。问题是我没有'DocumentRepository'库,我不明白什么是'context。也许是字节[]?我在工作中使用 VS2010,因为我使用的是无法运行最新版本的旧 PC。
  • pdfBytes 只是一个字节 [],因此您可以直接从数据库中提取它并使用其余代码或类似的代码来发回响应。
  • DocumentRepository 只是一个示例,它是负责获取 PDF 并将其转换为字节 [] 的代码或方法。 context.Response 只是您的 HTTP 上下文。当您提供对 http 请求的响应时,您通常会填写 HTTP 响应代码(即 200 OK)、内容类型,当然还有 html 的正文。给你的回复主要是你需要设置这3个,才能让另一端的客户端识别出已经成功的http请求(通过状态码)以及来了什么样的数据(定义按内容类型)
【解决方案2】:

你可以试试这个:

SqlConnection conn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=pubs;");
SqlCommand cmd = new SqlCommand("SELECT fileID, filePDF FROM myFiles", conn);   //filePDF is BLOB column

FileStream fs;                          // Writes the BLOB to a file
BinaryWriter bw;                        // Streams the BLOB to the FileStream object.

int bufferSize = 1000;                  // Max dimension of your PDF file in bytes.
byte[] outbyte = new byte[bufferSize];  // The BLOB byte[] buffer to be filled by GetBytes.
long retval;                            // The bytes returned from GetBytes.
long startIndex = 0;                    // The starting position in the BLOB output.

string fileID = "";                     // The publisher id to use in the file name.

// Open the connection and read data into the DataReader.
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);

while (myReader.Read())
{
  fileID = myReader.GetString(0);  

  fs = new FileStream("file_pdf" + fileID + ".pdf", FileMode.OpenOrCreate, FileAccess.Write);
  bw = new BinaryWriter(fs);

  startIndex = 0;

  retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);

  while (retval == bufferSize)
  {
    bw.Write(outbyte);
    bw.Flush();

    startIndex += bufferSize;
    retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);
  }

  bw.Write(outbyte, 0, (int)retval - 1);
  bw.Flush();

  bw.Close();
  fs.Close();
}

myReader.Close();
conn.Disponse();
conn.Close();

【讨论】:

  • 这确实是我想要的。到目前为止,我已经找到了这个示例并设法读取 blob,写入 pdf 文件,然后从本地磁盘打开、读取并返回 pdf 文件。我要避免的步骤是将pdf写入本地文件,然后将其作为文件打开。
  • @nasos 好的,我明白了!要阅读 PDF 文件,您可以使用 iTextSharp 并“提取”到新文件
【解决方案3】:

结合此处的一些信息和其他答案,我设法解决了我的问题。通常,我想避免将 BLOB 中的 PDF 作为物理文件写入,然后必须将其作为文件打开和读取。感谢您的帮助!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Configuration;
using MySql.Data.MySqlClient;
using System.IO;

public MySqlConnection myInit()
{
    return new MySqlConnection(
        "host=" + ConfigurationManager.AppSettings["mysqlHost"] +
        ";user=" + ConfigurationManager.AppSettings["mysqlUser"] +
        ";password=" + ConfigurationManager.AppSettings["mysqlPass"] +
        ";database=" + ConfigurationManager.AppSettings["mysqlDb"]);
}

public Dictionary<string,byte[]> getPDF(int pdfid)
{
    string query = "SELECT md5_string, data FROM pdf,pdf_view WHERE pdf.id=" + pdfid + " and pdf_view.id=pdf.id";
    MySqlConnection con = myInit();
    MySqlCommand cmd = new MySqlCommand(query, con);

    MemoryStream ms;
    BinaryWriter bw;                        // Streams the BLOB to the MemoryStream object.
    Dictionary<string, byte[]> result = new Dictionary<string, byte[]>();

    int bufferSize = 1000;                   // Size of the BLOB buffer.
    byte[] outbyte = new byte[bufferSize];  // The BLOB byte[] buffer to be filled by GetBytes.
    long retval;                            // The bytes returned from GetBytes.
    long startIndex = 0;

    con.Open();

    MySqlDataReader myReader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);

    while (myReader.Read())
    {
        ms = new MemoryStream();
        bw = new BinaryWriter(ms);

        string md5 = myReader.GetString(0);

        // Reset the starting byte for the new BLOB.
        startIndex = 0;

        // Read the bytes into outbyte[] and retain the number of bytes returned.
        retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);

        // Continue reading and writing while there are bytes beyond the size of the buffer.
        while (retval == bufferSize)
        {
            bw.Write(outbyte);
            bw.Flush();

            // Reposition the start index to the end of the last buffer and fill the buffer.
            startIndex += bufferSize;
            retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);
        }

        // Write the remaining buffer.
        bw.Write(outbyte, 0, (int)retval - 1);
        bw.Flush();

        result.Add(md5, ms.ToArray());

        // Close the output stream.
        bw.Close();
        ms.Close();
    }

    // Close the reader and the connection.
    myReader.Close();
    con.Close();

    return result;
}

我将它与 PHP 一起使用,如下所示:

$o = new SoapClient('http://localhost:3153/IntranetConnect.svc?wsdl', array('trace' => 0, 'cache_wsdl' => WSDL_CACHE_NONE));
$pdf = $o->getPDF(array('pdfid' => 1109));

foreach($pdf->getPDFResult as $value) {
   header("Content-type: application/pdf");
   header('Content-disposition: filename='.$value->Key.'.pdf');
   echo $value->Value;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-01
    • 2015-12-03
    • 2018-09-04
    • 2019-08-17
    • 1970-01-01
    • 2010-10-01
    • 2018-06-25
    • 1970-01-01
    相关资源
    最近更新 更多