C# Web Service 将存储为 BLOB 的 PDF 返回为 PDF

本文关键字:PDF BLOB 返回 存储 Web Service | 更新日期: 2023-09-27 18:35:45

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

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

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

谢谢!

(我有很强的PHP背景,但我发现将这种背景"翻译"为VS有些困难)

C# Web Service 将存储为 BLOB 的 PDF 返回为 PDF

首先 - 为什么不是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);

你可以试试这个:

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 作为物理文件写入,然后必须将其作为文件打开和读取。感谢您的帮助!

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