Read file from database

I saved the txt file as a string in a database column. Now in one of my aspx pages I have a link ... I want to open a txt file when a user clicks on that link. How can I read a file from a database. I know how to do this using a streamreader for a file stored on disk.

thank

0


source to share


4 answers


If you really need to save the file to the database (and I totally agree with Will on this, you shouldn't), you might consider implementing a separate download page (like getfile.aspx) that is responsible for getting a string from the database based on identifier, possibly (getfile.aspx? fileId = 12345), setting the appropriate HTTP headers, and outputting the content directly to the browser. By setting the title of the content type, you have to force the browser to see the aspx page as a txt file or any other recognized file format.



I would highly recommend changing the project scope to not store the file in the DB, however, as this method can get very confusing.

+2


source


This will require clarification.

If the file is stored as a string in the database, all you have to do is read it in string and display it on the page.

public void Page_Load(object sender, EventArgs e)
  var text = (from x in dataContext.MyTextTable where x.Id == someId select x.FileText).FirstOrDefault();

  this.textBox.Text = text;
}

      


Ok, here's what you need to do. Below is the pseudocode:



Load string from database
Use ToCharArray () method on string to get character array Use HttpResponse object to write () char array to response stream

Here's some almost compiled code:

public void Page_Load(object sender, EventArgs e)
{
  var text = Repository.GetTextFile(this.FileTextBox.Text).ToCharArray();

  Response.Clear();
  Response.AddHeader("Content-Disposition", "attachment; filename=" & this.FileTextBox.Text);
  Response.AddHeader("Content-Length", text.Length.ToString());
  Response.ContentType = "application/octet-stream";
  Response.Write(text, 0, text.length);
  Response.End();
}

      

I believe that the mime type should be rather than text / plain, since the browser might try to open the file rather than save it as an attachment.

+1


source


it covers the database and the blob type ... should be helpful.

http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx

+1


source


Why do you want to store the file in a database column? Databases are better for what you really need to query ... This is useful for queries such as "give me all links in the last 30 days" or "get all blue cars with cloth decorations".

Files are simply better handled by the OS file system. If you have a file entry, you can put the entry and instead put the file path in a row column.

0


source







All Articles