C#Web服务将存储为BLOB的PDF返回到PDF

C#Web服务将存储为BLOB的PDF返回到PDF,c#,web-services,pdf,C#,Web Services,Pdf,我对C#(和visualstudio)很陌生。到目前为止,我已经成功部署了一个从本地MSSQL服务器读取数据的WEB服务,但我想用VS2010扩展它 我有一个本地mySQL数据库,其中有一个BLOB列,存储一个PDF文件。我想阅读这篇BLOB专栏文章,并从web服务以PDF文件的形式返回结果。该服务将从PHP调用,在类似的情况下,我能够毫不费力地呈现PDF 到目前为止,通过谷歌搜索,我能够读取数据并将其存储为本地文件。我不希望将数据存储在文件中,而是将其存储在变量中(哪种类型?),因此我可以将此

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

我有一个本地mySQL数据库,其中有一个BLOB列,存储一个PDF文件。我想阅读这篇BLOB专栏文章,并从web服务以PDF文件的形式返回结果。该服务将从PHP调用,在类似的情况下,我能够毫不费力地呈现PDF

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

谢谢大家!


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

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

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

如果您将其作为mime类型添加到输出中,您应该可以自由使用:

i、 e:

您可以尝试以下方法:

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

您是如何实现web服务的?ASP.net?MVC?WCF服务应用程序。我只是将它复制到本地IIS,然后从PHP应用程序调用它。这听起来不错,谢谢。问题是我没有“DocumentRepository”库,也不知道什么类型是“context”。可能是字节[]?我在工作中使用VS2010是因为我使用的是一台无法运行最新版本的旧电脑。pdfBytes只是一个字节[],因此您可以直接从数据库中提取它,并使用其余代码或类似代码发回响应。DocumentRepository只是一个示例,它是负责获取PDF并将其转换为字节[]的代码或方法。响应只是您的HTTP上下文。当您提供对http请求的响应时,通常需要填写http响应代码(即200 OK)、内容类型,当然还有html正文。回复您的主要部分是,您需要设置这3个参数,以便另一端的客户端能够识别出它已经发出了一个成功的http请求(通过状态代码)以及正在发送的数据类型(通过内容类型定义),这确实是接近我想要的。我已经找到了这个例子,并设法读取blob,编写pdf文件,然后从本地磁盘打开、读取并返回pdf文件。我想避免的步骤是将pdf写入本地文件,然后将其作为文件打开。@nasos好的,我明白了!要读取PDF文件,您可以使用iTextSharp并将其“提取”到新文件
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;
}
$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;
}