I develop a student information system.I inser the PDF file to the database as a binary for each course.I want users to download this file.Downloading file but not displaying.Where am I doing wrong.
MvcCode
public FileResult FileDownload(Ders not)
{
byte[] byteArray = GetPdfFromDB(not.DersId);
MemoryStream pdfStream = new MemoryStream();
pdfStream.Write(byteArray, 0, byteArray.Length);
pdfStream.Position = 0;
//return new FileStreamResult(pdfStream, "application/pdf");
return File(pdfStream, "application/pdf", "DersNot.pdf");
}
private byte[] GetPdfFromDB(int id)
{
#region
byte[] bytes = { };
using (SqlConnection con = new SqlConnection(#"Server=****;Database=***;UID=***;PWD=***"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT DersNotIcerik FROM Ders WHERE DersId=#Id";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows == true)
{
sdr.Read();
bytes = (byte[])sdr["DersNotIcerik"];
}
}
con.Close();
}
}
return bytes;
#endregion
}
View
#Html.ActionLink(item2.DersNotAd, "FileDownload", new { id = item2.DersId })
I solved the problem like this.We can close the subject
public FileResult FileDownload(int id)
{
SqlConnection con = new SqlConnection(#"Server=10UR\MSSQLSERVERR;Database=UniversiteDB;UID=onur;PWD=1234");
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT DersNotIcerik FROM Ders WHERE DersId=#Id";
cmd.Parameters.AddWithValue("#Id", id);
byte[] binaryData = (byte[])cmd.ExecuteScalar();
return File(binaryData, "application/octet-stream", "DersNot.pdf");
}
Related
I want to fetch an image from the database and show it in my react-native app.where I did go wrong?
public IActionResult DownloadFile(int id)
{
DataTable table = new DataTable();
string query = #"select image from mydb.courses where id=#id";
string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");
MySqlDataReader myReader;
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
mycon.Open();
using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
{
myReader = myCommand.ExecuteReader();
table.Load(myReader);
var fs = new FileStream(myReader, FileMode.Open);
return File(fs, "application/octet-stream");
myReader.Close();
mycon.Close();
}
}
}
I fixed it.
[HttpGet("{id}")]
public IActionResult DownloadFile(int id)
{
string pathImage = "";
DataTable table = new DataTable();
string query = #"select image from mydb.courses where id=#id";
string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");
MySqlDataReader myReader;
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
mycon.Open();
using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
{
myCommand.Parameters.AddWithValue("#id", id);
pathImage = (string)myCommand.ExecuteScalar();
mycon.Close();
}
}
var path = #$"{pathImage}";
var fs = new FileStream(path, FileMode.Open);
return File(fs, "image/jpeg");
}
i'm created a database(with VS wizard) which contains 2 columns : Id , fData ;; fData type is nvarchar(MAX).
and then i insert a file into with this command :
public void InsertToDB()
{
byte[] data = File.ReadAllBytes(barcodeEXE); //this is an exe file
string base64 = Convert.ToBase64String(data);
mytbl3TableAdapter.Insert(1, base64);
mytbl3TableAdapter.Fill(mydb3DataSet.mytbl3);
//FILE ADDED !
}
now everythings is ok(file added into database with base64string format and we don't need to use those commands to insert file again) problem is here: i will copy the data from database to other folder with this commands :
public void CopyFromDB()
{
con = new SqlConnection();
con.ConnectionString = CnString;
con.Open(); //start
SqlCommand cmd = new SqlCommand("SELECT fData FROM [mytbl3] WHERE Id=1", con);
using (SqlDataReader d = cmd.ExecuteReader())
{
string base64;
base64 = ((string)mydb3DataSet.Tables[0].Rows[0]["fData"]);
byte[] base64byte = Convert.FromBase64String(base64);
mytbl3TableAdapter.Update(mydb3DataSet.mytbl3);
mytbl3TableAdapter.Fill(mydb3DataSet.mytbl3);
SaveFileDialog ofd = new SaveFileDialog(); ofd.Filter = "exe file|*.exe";
if (ofd.ShowDialog() == DialogResult.OK)
{
File.WriteAllBytes(ofd.FileName, base64byte);
System.Threading.Thread.Sleep(3000);
d.Close();
//
}
d.Close();
}
//end
con.Close();
}
the file will copy successfully but data will remove from database!!
The CopyFromDB function looks to be not doing what you intend to:
public void CopyFromDB()
{
con = new SqlConnection();
con.ConnectionString = CnString;
con.Open(); //start
SqlCommand cmd = new SqlCommand("SELECT fData FROM [mytbl3] WHERE Id=1", con);
using (SqlDataReader d = cmd.ExecuteReader())
{
if (d.Read())
{
string base64;
base64 = reader.GetString(d.GetOrdinal("fData"));
byte[] base64byte = Convert.FromBase64String(base64);
SaveFileDialog ofd = new SaveFileDialog(); ofd.Filter = "exe file|*.exe";
if (ofd.ShowDialog() == DialogResult.OK)
{
File.WriteAllBytes(ofd.FileName, base64byte);
System.Threading.Thread.Sleep(3000);
}
}
d.Close();
//end
con.Close();
}
}
I have done inserting image into database and the datatype is image, but when I want to retrieve it, it is very difficult and error will show Parameter is not valid.
public void RetrieveImage()
{
var con = new SqlConnection(Connection.CATAS_LOCAL());
string SQL = "Select Name,Image from dbo.[TestImage] where Name = 'Test1'";
var cmd = new SqlCommand(SQL, con);
con.Open();
SqlDataReader Reader = cmd.ExecuteReader();
Reader.Read();
if (Reader.HasRows)
{
txtAddStaffNric.Text = Reader[0].ToString();
byte[] img = (byte[])(Reader[1]);
MemoryStream ms = new MemoryStream(img);
pictureBox2.Image = Image.FromStream(ms); ** error show at this line
}
con.Close();
}
I have the following method i am using to save an object into an SQL Server CE database. I am now stuck on how to get the record back out.
public void SaveRecord(LabRecord _labrecord)
{
try
{
conn = new SqlCeConnection(_connectionString);
conn.Open();
MemoryStream memStream = new MemoryStream();
StreamWriter sw = new StreamWriter(memStream);
sw.Write(_labrecord);
SqlCeCommand sqlCmd = new SqlCeCommand("INSERT INTO LabTransactions([TrasactionType], [CAM], [TransactionObject]) VALUES ('ResultTest', 1234, #Image)", conn);
sqlCmd.Parameters.Add("#Image", SqlDbType.Image, Int32.MaxValue);
sqlCmd.Parameters["#Image"].Value = memStream.GetBuffer();
sqlCmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
Update
I am looking to make another class that returns a specific record.
public LabRecord getRecord(int transactionId)
{
LabRecord returnRecord = null;
try
{
conn = new SqlCeConnection(_connectionString);
conn.Open();
//.... Get the record
}
finally
{
conn.Close();
}
return returnRecord;
}
I think the problem most likely lies in the fact that the size of the #Image parameter is being set to Int32.MaxValue
Set it instead to the length of the image byte stream:
byte[] imgBytes = memStream.GetBuffer();
sqlCmd.Parameters.Add("#Image", SqlDbType.Image, imgBytes.Length);
sqlCmd.Parameters["#Image"].Value = imgBytes;
Here's an excerpt from this example (modified for your question) of how you might go about retrieving the image:
// Get the record
SqlCeCommand cmd = new SqlCeCommand("Select [TransactionObject] From LabTransactions Where [CAM] = 1234", conn);
conn.Open();
SqlCeDataReader sdr = cmd.ExecuteReader();
byte[] imgByteData = Convert.ToByte(sdr.Item("Picture"));
Bitmap bitmap = new Bitmap(new System.IO.MemoryStream(imgByteData));
I am doing a 3 tier application to retrieve image from sql server which i stored image to binary data in sql, and the problem is i can't retrieve my image from the sql server.
here is my code in DataAccessLayer
public List<Volunteer> VolunteerTRetrieve()
{
List<Volunteer> vList = new List<Volunteer>();
byte[] volunteerProfilePicture;
string volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact;
string queryStr = "SELECT * FROM TVolunteer Order By VolunteerName";
SqlConnection conn = new SqlConnection(DBconnStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while ((dr.Read()))
{
volunteerName = dr["VolunteerName"].ToString();
volunteerNRIC = dr["VolunteerNRIC"].ToString();
volunteerAddress = dr["VolunteerAddress"].ToString();
volunteerEmail = dr["VolunteerEmail"].ToString();
volunteerContact = dr["VolunteerContact"].ToString();
volunteerProfilePicture = (byte[])dr["VolunteerProfilePicture"];
vList.Add(new Volunteer(volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact, volunteerProfilePicture));
}
conn.Close();
dr.Dispose();
return vList;
}
in BusinessLogicLayer
public List<Volunteer> RetrieveAllBVolunteer()
{
Volunteer v = new Volunteer();
List<Volunteer> vList = new List<Volunteer>();
vList = v.VolunteerBRetrieve();
return vList;
}
and in PresentationLayer
List<Volunteer> allVolunteer = new List<Volunteer>();
allVolunteer = vBLL.RetrieveAllTVolunteer();
dl_tvolunteer.DataSource = allVolunteer;
dl_tvolunteer.DataBind();
I have also an image handler class
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["DBconnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string queryStr = "SELECT VolunteerProfilePicture FROM TVolunteer WHERE VolunteerNRIC = #NRIC";
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.Add("#NRIC", SqlDbType.VarChar).Value =
context.Request.QueryString["VolunteerNRIC"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["VolunteerProfilePicture"]);
}
Please help, Thankyou!
If you are returning one image you could the following
1. place a PictureBox control on the asp.net webpage
2. define the sql connections //not sure why you are using cmd.prepare
byte[] sqlImage = (byte[])cmd.ExecuteScalar();
MemoryStream memStream = new MemoryStream();
memStream.Write(sqlImage, 0, sqlImage.Length);
Bitmap bit = new Bitmap(memStream);
or if you want to do it a different way
try
{
con = new SqlConnection(constr);
cmd = new SqlCommand("select photopath,Photo from employees where employeeid=14", con);
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if (!dr.IsDBNull(1))
{
byte[] photo = (byte[])dr[1];
MemoryStream ms = new MemoryStream(photo);
pictureBox1.Image = Image.FromStream(ms);
}
}
}
catch (Exception ex)
{
dr.Close();
cmd.Dispose();
con.Close();
Response.Write(ex.Message);
}