Saving image file into the database - c#

how can i save the file using c# into the SQL server dataqbase after user has selected the file location using fileupload control in asp.net .

Please look into this article Save Files to SQL Server Database using FileUpload Control

I would love if you first search on gooogle and than ask for the help if you find out difficult to understand anyways check the following article help you to achieve your task
C# Save and Load Image from Database

You might try something like this:
if (this.fileUploader.PostedFile == null ||
this.fileUploader.PostedFile.ContentLength < 1)
{
this.LabelError.Text = this.GetGlobalResourceObject("Messages", "NoFileToUpload")
.ToString();
return;
}
MyTableWithImageField i = new MyTableWithImageField();
i.ImageData = this.fileUploader.FileBytes;
command.CommandText = #"InsertMyTableWithImageField";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#ImageData", i.ImageData);
You may also want to check this from MSDN: Uploading Files in ASP.NET 2.0

Related

How I can save *.docx file in sql server and show it

I have some problem. I'am try to save *.docx fail in sql server and show it in web-site. I can save my file in sql server using this code
Byte[] bytes = File.ReadAllBytes(varFilePath);
String file = Convert.ToBase64String(bytes);
using (SqlConnection sql_connetion = new SqlConnection(ConfigurationManager.ConnectionStrings["Database_connection"].ConnectionString))
{
sql_connetion.Open();
using (var sqlWrite = new SqlCommand("INSERT INTO use_of_rule (ID, taj) Values('3', #File)", sql_connetion))
{
sqlWrite.Parameters.Add("#File", bytes);
sqlWrite.ExecuteNonQuery();
return "ok";
}
}
I want to display the content of the file in the web browser. How I can do it?
If you are using Word from WAS (Office Web App Server), you need to do something like this:
1 Create a simple web site to read the data from sql.
You could create a Generic Handler (ashx) in ASP.Net site, providing the plain word file data as response. Dont forget to set the content type as "application/vnd.openxmlformats-officedocument.wordprocessingml.document".
2 Use url encoding to encode the link created in step 1, including all parameters you may want to pass into it.
3 To launch Word, you need to nav it to http(s)://your.was.server.name/op/view.aspx?src=paste.encoded.url.here

Save Outlook .ics file to sql database

I am trying to figure out how to allow my users to be able to save their outlook files to a sql database using c#/.net. I am using a normal file upload control and what I thought was I could just save it is a string but and put in a link button but that didn't work for me.
This was my idea for the code:
string ImageName1 = string.Empty;
byte[] Image1 = null;
if (Images1.PostedFile != null && Images1.PostedFile.FileName != "")
{
ImageName1 = Path.GetFileName(Images1.FileName);
Image1 = new byte[Images1.PostedFile.ContentLength];
HttpPostedFile UploadedImage = Images1.PostedFile;
Images1.PostedFile.InputStream.Read(Image1, 0, Images1.PostedFile.ContentLength);
UploadedImage.InputStream.Read(Image1, 0, (int)Images1.PostedFile.ContentLength);
}
Any information on how to do that would be helpful!
You can store files as BLOBs in the database.
I don't quite follow your code, normally you call a stored procedure and pass parameters or specify the command as text in c# for communicating with the SQL server.
This link gives an example of how to insert blob into database.

Retrieve Image from MySQL Database over Server

I am making a program which requires getting the local directory of an image from a MySQL database table. For the moment, I have made the directory of the image I want to retrieve equal to C:\Users\User\Pictures\PictureName.PNG in the MySQL table. The method I have written up is able to retrieve this data from the database through a Select statement and set the PictureBox image as a new Bitmap with the path retrieved from the Selectstatement.
I couldn't find the information I was looking for online as most of the answers relate to using the BLOB field in MySQL to store images, but my question is if I were to put my database on a server and with the pictures on there too, would my method scale to accommodate for those changes or would I have to add other functionality in order for it to work on a server as well?
Here is my code below:
public void setImage() {
string path = sql.RetrieveImage(SelectQuery.RetrievePicture());
PictureBox1.Image = new Bitmap(path);
}
public string RetrieveImage(Query query) {
string path = "";
// OpenDatabaseConnection() will open up a connection to the database
// through connection and if successful, will return true.
if (this.OpenDatabaseConnection()) {
// query.ToSql() returns a string format of the select statement
// required to retrieve the local image directory
using (MySqlCommand cmd = new MySqlCommand(query.ToSql(), connection)) {
MySqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
path = dataReader[0] + "";
dataReader.Close();
}
this.CloseDatabaseConnection();
}
return path;
}
Storing images in a DB is a bad idea. Storing paths to image files is a much better way to go, IMO.
This SO question has a few links to really good supporting information.
If you must go that route, however, then yes, the BLOB field (or a VarBinary(MAX) in SQLServer) is the way to do it. You can retrieve those images as Byte[] data.

Ensure 2 methods succeed else roll back

Can anyone please tell me whether this is possible.
I have some code that allows a user to upload/change their image, before the change takes place I delete the default/old image from disk before uploading new image.
Problem is if something goes wrong either with the delete or upload, how can I roll back both so that the original image is returned.
I thought I could use tranactionscope, but either I'm not using it correctly or it not applicable for this case.
All the examples I have found involve using 2 call to database, but my code only involves one call and that's to update.
//TODO check transactionscope works ok
using (var tran = new TransactionScope())
{
//Delete old image before updating new image
//123 bogus number to throw error
var deleteOldImage = _igmpfu.DisplayProfileDetailsForUpdate("123")
.FirstOrDefault();
if (Convert.ToString(deleteOldImage) !=
"5bb188f0-2508-4cbd-b83d-9a5fe5914a1b.png")
{
DeleteOldImage(deleteOldImage);
}
//Insert new image
var imageGuid = imageId + ".png";
bool imageUrl = _iuma.UpdateAvatar(cookieId, imageGuid);
if (imageUrl)
{
TempData["Message"] = "Image updated";
return RedirectToAction("Index", "Members");
}
tran.Complete();
}
Any assistance in helping a newbie would be appreciated
//------------------------
I have been looking at the computer to long, all I had to do was
var deleteOldImage = _igmpfu.DisplayProfileDetailsForUpdate("123").FirstOrDefault();
if (deleteOldImage != null)
{
code here for writing to disk
}
I have spent ages trying to work this out and thats all I had to do :-(
Thanks everyone for their replies.
The code you have would only work if the classes you are using know how to enlist in the transaction.
The main issue you will encounter when dealing with files is that the file system is difficult to deal with transactionally. The approach I would use is this:
Save the new file on disk with a different filename.
Update the database with the new filename.
If the db update was successful, delete the old file from disk, if not delete the new file from disk.

ASP.NET MVC Website Read File from Disk Problem

I'm reading a text file containing an insert statement for SQL using C# in an MVC Website I'm working on. When debugging the function I'm using works fine and the insert occurs. But once I publish the site and run it on my local machine (with IIS set-up to use asp.net 4.0 even) it doesn't seem to work.
if (Request.Files != null && Request.Files["txtImportFile"] != null)
{
//newFilePath = Server.MapPath("\\" + DateTime.Now.Ticks + Request.Files["txtImportFile"].FileName);
string[] temp_string = Request.Files["txtImportFile"].FileName.Split(new char[] { '\\' });
string temp_filename = temp_string[temp_string.Count() - 1];
//newFilePath = Server.MapPath("\\temp\\" + DateTime.Now.Ticks + Request.Files["txtImportFile"].FileName);
newFilePath = Server.MapPath("\\temp\\" + DateTime.Now.Ticks + temp_filename);
Request.Files["txtImportFile"].SaveAs(newFilePath);
StreamReader reader = new StreamReader(newFilePath);
string contents = reader.ReadToEnd();
reader.Close();
Models.WingsRemoteDbLibrary dbLib = new Models.WingsRemoteDbLibrary();
string update_message = dbLib.UpdateSlaveItemsTable(contents);
if (System.IO.File.Exists(newFilePath))
System.IO.File.Delete(newFilePath);
RandomPopupView(update_message);
}
I hope my explanation doesn't sound vague. I'll try my best to answer any further questions. Thanks.
Workaround:
Instead of using
Server.MapPath("\\temp\\"...
Create folder under root with name "temp" and use
System.Web.HttpContext.Current.Request.MapPath("~\\temp....
Well, "it doesn't seem to work" is pretty vague - a bit more detail would be nice! But it sounds like a permissions issue. The default profile in IIS has very little access to the disk, especially write access. It isn't really a good idea to write inside your own site anyway (I'd use an unrelated part of the disk, myself), but you will need to configure IIS to run the application in a specific named identity, with access to the disk. Configuring the account itself (not IIS - the account; for example granting "logon as a service") to run as an ASP.NET account is not particularly trivial, unfortunately.
Another thought: is your app a sub-application, i.e. is your app-root /, or is it /MyApp/ ? The reason I ask is your use of MapPath might be better expressed relative to the app-root, i.e. ~/temp/ - but again I stress; writing inside the app is risky. You really want that folder to be non-executing.
There may be an alternative solution to this problem. You can avoid messing with path and file system altogether if you can 'bake' the file into assembly at build time. Here is how you can do this:
In Visual Studio solution explorer right click on a file and go to Properties.
Set Build Action to 'Embedded Resource'.
Later you can read the file using GetManifestResourceStream:
var stream = GetType()
.Assembly
.GetManifestResourceStream("YourNameSpace.Folder.YourFile.txt");
using (var reader = new StreamReader(stream)) {
var fileContent = reader.ReadToEnd();
}
More info here.

Categories