1

in my webapp I've created and populated a stringbuilder for a csv file. Normally I write it directly to the response object for the user to download through the browser. However, now I want to save it to a SQL DB image field. Is there a direct way to stream it in? Or do I have to save it to file first, then read it back in?

TIA folks!

dodgeyb
  • 11
  • 1

3 Answers3

0

Just pass sb.ToString() to your parameter. It's only text.

Mike Brind
  • 28,238
  • 6
  • 56
  • 88
0

I assume that you only mention the Stringbuilder and CSV file because that refers to your previous experiences with enabling file downloads to users.

It is a little bit unclear whether you want to receive the image file from the user or provide the image file for the user to download? I have therefore provided the solution to both questions.

How do you return an image from SQL Server with the httpResponse?

  1. Get the image data from the database
  2. Set the correct content-type of the response (e.g. image/jpg, image/gif or image/png)
  3. Write the bytes of your image to the raw response stream

Here is a relevant thread with some code samples: How to load an image in ASP.NET from a database as a file in a web browser?

As specified in the preferred answer you should consider implementing an httpHandler to provide the images rather than serving them throug an ASPX-page (which is intended for html)

How do you enable image file upload to a SQL server database?

If you want to save an image file received from a file input control into a database then you should check out this link: How do you store a picture in an image column?

Community
  • 1
  • 1
Simen S
  • 3,210
  • 18
  • 24
0

First, why do you want to store text data as an image (= binary = byte array) data type?

If you use an n/text or n/varchar(max) column, you can pass the result of the StringBuilder's ToString() method to your insert statement as parameter.

If you really really insist on storing text as a binary field, use the Encoding.GetBytes() method of your preferred encoding to retrieve the byte array.

devio
  • 36,858
  • 7
  • 80
  • 143
  • Thanks for the answer, I ended up doing the getBytes thing and its working now. I'm storing the text in an image field because the CSV can be v.large, & I wasn't sure of the capacity of varchar(max)? Would keeping it as text be the preferred option? Cheers – dodgeyb Mar 27 '11 at 06:28
  • image and varchar(max) are both limited to 2GB. http://msdn.microsoft.com/en-us/library/ms187993.aspx – devio Mar 27 '11 at 09:05