CONVERT OBJECT TO BYTE[]
Hello how are you? I'm having difficulties in converting an object (returned by a query to the Postgres database) to byte[], I test in several different ways but I can't get the total size of the array stored in the database referring to the image. I have a single image saved in the database, and in each way I try to retrieve it, the byte[] comes with a different size depending on how I do the conversion from object to byte[]. The biggest array size I got was length = 42, the image has length = 675486. I've tried these ways.
using (conexao)
{
string sQL = " SELECT p.photo_img " +
" FROM empresa as e, photo as p " +
" WHERE e.empresa_img = " + id + " AND " +
" e.empresa_img = p.photo_id; ";
using (var command = new NpgsqlCommand(sQL, conexao))
{
byte[] productImageByte = null;
conexao.Open();
var rdr = command.ExecuteReader();
while (rdr.Read())
{
productImageByte = (byte[])rdr[0];
}
rdr.Close();
if (productImageByte != null)
{
using (MemoryStream productImageStream = new MemoryStream(productImageByte))
{
ImageConverter imageConverter = new System.Drawing.ImageConverter();
pct_Imagem.Image = imageConverter.ConvertFrom(productImageByte) as System.Drawing.Image;
}
}
}
}
The result of this was length = 13
private void dgv_empresa_CellClick(object sender, DataGridViewCellEventArgs e)
{
int id = Convert.ToInt32(dgv_empresa.SelectedCells[0].OwningRow.Cells[9].Value);
if (id != 0)
{
try
{
string query = " SELECT p.photo_img " +
" FROM empresa as e, photo as p " +
" WHERE e.empresa_img = " + id + " AND " +
" e.empresa_img = p.photo_id; ";
conexao.Open();
DataTable dados = new DataTable();
NpgsqlDataAdapter adaptador = new NpgsqlDataAdapter(query, conexao);
adaptador.Fill(dados);
if (dados.Rows.Count > 0)
{
foreach (DataRow linha in dados.Rows)
{
byte[] data = ObjectToByteArray(linha[0]);
var imagem = (Image)new ImageConverter().ConvertFrom(data);
pct_Imagem.Image = imagem;
}
}
}
catch (Exception ex)
{
conexao.Close();
MessageBox.Show(ex.Message, "Erro no Banco de Dados!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
conexao.Close();
}
}
}
byte[] ObjectToByteArray(object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
The result of this was length = 42
These last two brought me the best results. But still, it's not a valid byte array. Can someone help me?
you can use this method that I serialized the class into JSON text and then converted it to byte[]. You can either serialize it to XML
private byte[] CreateByteArray(object obj)
{
using var memoryStream = new MemoryStream();
using var writer = new StreamWriter(memoryStream);
var jsonText = JsonConvert.SerializeObject(obj);
writer.WriteAsync(jsonText);
writer.Flush();
return memoryStream.ToArray();
}
I managed to do, what I needed to adjust to not use Connetion, but create and discard in each block that was to be used
By Below Procedure I am Displaying Image to Crystal Report
First: I created a New Column ("Image") in a datatable of the dataset and change the DataType to System.Byte()
Second : Drag And drop this image Filed Where I want.
private void LoadReport()
{
frmCheckWeigher rpt = new frmCheckWeigher();
CryRe_DailyBatch report = new CryRe_DailyBatch();
DataSet1TableAdapters.DataTable_DailyBatch1TableAdapter ta = new CheckWeigherReportViewer.DataSet1TableAdapters.DataTable_DailyBatch1TableAdapter();
DataSet1.DataTable_DailyBatch1DataTable table = ta.GetData(clsLogs.strStartDate_rpt, clsLogs.strBatchno_Rpt, clsLogs.cmdeviceid); // Data from Database
DataTable dt = GetImageRow(table, "Footer.Jpg");
report.SetDataSource(dt);
crv1.ReportSource = report;
crv1.Refresh();
}
// By this Function I merge My Image data into dataTable
private DataTable GetImageRow(DataTable dt, string ImageName)
{
try
{
FileStream fs;
BinaryReader br;
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + ImageName))
{
fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + ImageName, FileMode.Open);
}
else
{
// if photo does not exist show the Blank Space or Show Nothing
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["Image"] = DBNull.Value ;
}
return dt;
}
// initialise the binary reader from file streamobject
br = new BinaryReader(fs);
// define the byte array of filelength
byte[] imgbyte = new byte[fs.Length + 1];
// read the bytes from the binary reader
imgbyte = br.ReadBytes(Convert.ToInt32((fs.Length)));
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["Image"] = imgbyte;
}
br.Close();
// close the binary reader
fs.Close();
// close the file stream
}
catch (Exception ex)
{
// error handling
MessageBox.Show("Missing " + ImageName + " in application folder");
}
return dt;
// Return Datatable After Image Row Insertion
}
this Works Perfectly when I have Image on path but
I want to Show Empty- blank Space when user Not Give Image on Specify path,
But I get blank Square as per given Image with border how to remove it please help me ..
Use the suppress function from the report it self,
Right click on the image object >> format object >> Fill the check box near the word suppress then click on the formula on the right of suppress then add the formula you require some thing like:
ISNULL({Class;1.Img})
How can I dynamically insert images when user uploads an image file to SQL Server 2005 with C# in ASP.NET? This is to let users upload their profile photos in my web app. Is it very different from how it is done for windows app with C#?
There is a metric ton of examples on the web on this one:
http://aspalliance.com/138
https://web.archive.org/web/20210304133428/https://www.4guysfromrolla.com/articles/120606-1.aspx
http://www.aspfree.com/c/a/ASP.NET/Uploading-Images-to-a-Database--C---Part-I/
You should be able to follow any of those to accomplish what you want.
The same way as in in WinForms. Get byte[] and same to image column. But i strongly recommend to use file system to store pictures. DB is for relational data, File System for raw bytes.
http://msdn.microsoft.com/en-us/library/aa479405.aspx
Here is a sample of the code behind for inserting an image into a database in C#. You will of coarse need supporting table the picture should be a byte field and keep the picture type so you can retrieve the image later to display it. In addition to that you need to put a file input box on your page along with a submit button.
public void AddImage(object sender, EventArgs e)
{
int intImageSize;
String strImageType;
Stream ImageStream;
FileStream fs = File.OpenRead(Request.PhysicalApplicationPath + "/Images/default_image.png");
Byte[] ImageContent;
if (PersonImage.PostedFile.ContentLength > 0)
{
intImageSize = PersonImage.PostedFile.ContentLength;
strImageType = PersonImage.PostedFile.ContentType;
ImageStream = PersonImage.PostedFile.InputStream;
ImageContent = new Byte[intImageSize];
int intStatus;
intStatus = ImageStream.Read(ImageContent, 0, intImageSize);
}
else
{
strImageType = "image/x-png";
ImageContent = new Byte[fs.Length];
fs.Read(ImageContent, 0, ImageContent.Length);
}
SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["conn"]);
SqlCommand objCmd;
string strCmd;
strCmd = "INSERT INTO ImageTest (Picture, PictureType) VALUES (#Picture, #PictureType)";
objCmd = new SqlCommand(strCmd, objConn);
SqlParameter prmPersonImage = new SqlParameter("#Picture", SqlDbType.Image);
prmPersonImage.Value = ImageContent;
objCmd.Parameters.Add(prmPersonImage);
objCmd.Parameters.AddWithValue("#PictureType", strImageType);
lblMessage.Visible = true;
try
{
objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
lblMessage.Text = "ImageAdded!";
}
catch
{
lblMessage.Text = "Error occured the image has not been added to the database!";
}
}
Is converting a file to a byte array the best way to save ANY file format to disk or database var binary column?
So if someone wants to save a .gif or .doc/.docx or .pdf file, can I just convert it to a bytearray UFT8 and save it to the db as a stream of bytes?
Since it's not mentioned what database you mean I'm assuming SQL Server. Below solution works for both 2005 and 2008.
You have to create table with VARBINARY(MAX) as one of the columns. In my example I've created Table Raporty with column RaportPlik being VARBINARY(MAX) column.
Method to put file into database from drive:
public static void databaseFilePut(string varFilePath) {
byte[] file;
using (var stream = new FileStream(varFilePath, FileMode.Open, FileAccess.Read)) {
using (var reader = new BinaryReader(stream)) {
file = reader.ReadBytes((int) stream.Length);
}
}
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlWrite = new SqlCommand("INSERT INTO Raporty (RaportPlik) Values(#File)", varConnection)) {
sqlWrite.Parameters.Add("#File", SqlDbType.VarBinary, file.Length).Value = file;
sqlWrite.ExecuteNonQuery();
}
}
This method is to get file from database and save it on drive:
public static void databaseFileRead(string varID, string varPathToNewLocation) {
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlQuery = new SqlCommand(#"SELECT [RaportPlik] FROM [dbo].[Raporty] WHERE [RaportID] = #varID", varConnection)) {
sqlQuery.Parameters.AddWithValue("#varID", varID);
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null) {
sqlQueryResult.Read();
var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
using (var fs = new FileStream(varPathToNewLocation, FileMode.Create, FileAccess.Write))
fs.Write(blob, 0, blob.Length);
}
}
}
This method is to get file from database and put it as MemoryStream:
public static MemoryStream databaseFileRead(string varID) {
MemoryStream memoryStream = new MemoryStream();
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlQuery = new SqlCommand(#"SELECT [RaportPlik] FROM [dbo].[Raporty] WHERE [RaportID] = #varID", varConnection)) {
sqlQuery.Parameters.AddWithValue("#varID", varID);
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null) {
sqlQueryResult.Read();
var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
//using (var fs = new MemoryStream(memoryStream, FileMode.Create, FileAccess.Write)) {
memoryStream.Write(blob, 0, blob.Length);
//}
}
}
return memoryStream;
}
This method is to put MemoryStream into database:
public static int databaseFilePut(MemoryStream fileToPut) {
int varID = 0;
byte[] file = fileToPut.ToArray();
const string preparedCommand = #"
INSERT INTO [dbo].[Raporty]
([RaportPlik])
VALUES
(#File)
SELECT [RaportID] FROM [dbo].[Raporty]
WHERE [RaportID] = SCOPE_IDENTITY()
";
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
using (var sqlWrite = new SqlCommand(preparedCommand, varConnection)) {
sqlWrite.Parameters.Add("#File", SqlDbType.VarBinary, file.Length).Value = file;
using (var sqlWriteQuery = sqlWrite.ExecuteReader())
while (sqlWriteQuery != null && sqlWriteQuery.Read()) {
varID = sqlWriteQuery["RaportID"] is int ? (int) sqlWriteQuery["RaportID"] : 0;
}
}
return varID;
}
While you can store files in this fashion, it has significant tradeoffs:
Most DBs are not optimized for giant quantities of binary data, and query performance often degrades dramatically as the table bloats, even with indexes. (SQL Server 2008, with the FILESTREAM column type, is the exception to the rule.)
DB backup/replication becomes extremely slow.
It's a lot easier to handle a corrupted drive with 2 million images -- just replace the disk on the RAID -- than a DB table that becomes corrupted.
If you accidentally delete a dozen images on a filesystem, your operations guys can replace them pretty easily from a backup, and since the table index is tiny by comparison, it can be restored quickly. If you accidentally delete a dozen images in a giant database table, you have a long and painful wait to restore the DB from backup, paralyzing your entire system in the meantime.
These are just some of the drawbacks I can come up with off the top of my head. For tiny projects it may be worth storing files in this fashion, but if you're designing enterprise-grade software I would strongly recommend against it.
It really depends on the database server.
For example, SQL Server 2008 supports a FILESTREAM datatype for exactly this situation.
Other than that, if you use a MemoryStream, it has a ToArray() method that will convert to a byte[] - this can be used for populating a varbinary field..
I'll describe the way I've stored files, in SQL Server and Oracle. It largely depends on how you are getting the file, in the first place, as to how you will get its contents, and it depends on which database you are using for the content in which you will store it for how you will store it. These are 2 separate database examples with 2 separate methods of getting the file that I used.
SQL Server
Short answer: I used a base64 byte string I converted to a byte[] and store in a varbinary(max) field.
Long answer:
Say you're uploading via a website, so you're using an <input id="myFileControl" type="file" /> control, or React DropZone. To get the file, you're doing something like var myFile = document.getElementById("myFileControl")[0]; or myFile = this.state.files[0];.
From there, I'd get the base64 string using code here: Convert input=file to byte array (use function UploadFile2).
Then I'd get that string, the file name (myFile.name) and type (myFile.type) into a JSON object:
var myJSONObj = {
file: base64string,
name: myFile.name,
type: myFile.type,
}
and post the file to an MVC server backend using XMLHttpRequest, specifying a Content-Type of application/json: xhr.send(JSON.stringify(myJSONObj);. You have to build a ViewModel to bind it with:
public class MyModel
{
public string file { get; set; }
public string title { get; set; }
public string type { get; set; }
}
and specify [FromBody]MyModel myModelObj as the passed in parameter:
[System.Web.Http.HttpPost] // required to spell it out like this if using ApiController, or it will default to System.Mvc.Http.HttpPost
public virtual ActionResult Post([FromBody]MyModel myModelObj)
Then you can add this into that function and save it using Entity Framework:
MY_ATTACHMENT_TABLE_MODEL tblAtchm = new MY_ATTACHMENT_TABLE_MODEL();
tblAtchm.Name = myModelObj.name;
tblAtchm.Type = myModelObj.type;
tblAtchm.File = System.Convert.FromBase64String(myModelObj.file);
EntityFrameworkContextName ef = new EntityFrameworkContextName();
ef.MY_ATTACHMENT_TABLE_MODEL.Add(tblAtchm);
ef.SaveChanges();
tblAtchm.File = System.Convert.FromBase64String(myModelObj.file); being the operative line.
You would need a model to represent the database table:
public class MY_ATTACHMENT_TABLE_MODEL
{
[Key]
public byte[] File { get; set; } // notice this change
public string Name { get; set; }
public string Type { get; set; }
}
This will save the data into a varbinary(max) field as a byte[]. Name and Type were nvarchar(250) and nvarchar(10), respectively. You could include size by adding it to your table as an int column & MY_ATTACHMENT_TABLE_MODEL as public int Size { get; set;}, and add in the line tblAtchm.Size = System.Convert.FromBase64String(myModelObj.file).Length; above.
Oracle
Short answer: Convert it to a byte[], assign it to an OracleParameter, add it to your OracleCommand, and update your table's BLOB field using a reference to the parameter's ParameterName value: :BlobParameter
Long answer:
When I did this for Oracle, I was using an OpenFileDialog and I retrieved and sent the bytes/file information this way:
byte[] array;
OracleParameter param = new OracleParameter();
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "Image Files (*.jpg, *.jpeg, *.jpe)|*.jpg;*.jpeg;*.jpe|Document Files (*.doc, *.docx, *.pdf)|*.doc;*.docx;*.pdf"
if (dlg.ShowDialog().Value == true)
{
string fileName = dlg.FileName;
using (FileStream fs = File.OpenRead(fileName)
{
array = new byte[fs.Length];
using (BinaryReader binReader = new BinaryReader(fs))
{
array = binReader.ReadBytes((int)fs.Length);
}
// Create an OracleParameter to transmit the Blob
param.OracleDbType = OracleDbType.Blob;
param.ParameterName = "BlobParameter";
param.Value = array; // <-- file bytes are here
}
fileName = fileName.Split('\\')[fileName.Split('\\').Length-1]; // gets last segment of the whole path to just get the name
string fileType = fileName.Split('.')[1];
if (fileType == "doc" || fileType == "docx" || fileType == "pdf")
fileType = "application\\" + fileType;
else
fileType = "image\\" + fileType;
// SQL string containing reference to BlobParameter named above
string sql = String.Format("INSERT INTO YOUR_TABLE (FILE_NAME, FILE_TYPE, FILE_SIZE, FILE_CONTENTS, LAST_MODIFIED) VALUES ('{0}','{1}',{2},:BlobParamerter, SYSDATE)", fileName, fileType, array.Length);
// Do Oracle Update
RunCommand(sql, param);
}
And inside the Oracle update, done with ADO:
public void RunCommand(string strSQL, OracleParameter param)
{
OracleConnection oraConn = null;
OracleCommand oraCmd = null;
try
{
string connString = GetConnString();
oraConn = OracleConnection(connString);
using (oraConn)
{
if (OraConnection.State == ConnectionState.Open)
OraConnection.Close();
OraConnection.Open();
oraCmd = new OracleCommand(strSQL, oraConnection);
// Add your OracleParameter
if (param != null)
OraCommand.Parameters.Add(param);
// Execute the command
OraCommand.ExecuteNonQuery();
}
}
catch (OracleException err)
{
// handle exception
}
finally
{
OraConnction.Close();
}
}
private string GetConnString()
{
string host = System.Configuration.ConfigurationManager.AppSettings["host"].ToString();
string port = System.Configuration.ConfigurationManager.AppSettings["port"].ToString();
string serviceName = System.Configuration.ConfigurationManager.AppSettings["svcName"].ToString();
string schemaName = System.Configuration.ConfigurationManager.AppSettings["schemaName"].ToString();
string pword = System.Configuration.ConfigurationManager.AppSettings["pword"].ToString(); // hopefully encrypted
if (String.IsNullOrEmpty(host) || String.IsNullOrEmpty(port) || String.IsNullOrEmpty(serviceName) || String.IsNullOrEmpty(schemaName) || String.IsNullOrEmpty(pword))
{
return "Missing Param";
}
else
{
pword = decodePassword(pword); // decrypt here
return String.Format(
"Data Source=(DESCRIPTION =(ADDRESS = ( PROTOCOL = TCP)(HOST = {2})(PORT = {3}))(CONNECT_DATA =(SID = {4})));User Id={0};Password={1};",
user,
pword,
host,
port,
serviceName
);
}
}
And the datatype for the FILE_CONTENTS column was BLOB, the FILE_SIZE was NUMBER(10,0), LAST_MODIFIED was DATE, and the rest were NVARCHAR2(250).
What database are you using? normally you don't save files to a database but i think sql 2008 has support for it...
A file is binary data hence UTF 8 does not matter here..
UTF 8 matters when you try to convert a string to a byte array... not a file to byte array.
Confirming I was able to use the answer posted by MadBoy and edited by Otiel on both MS SQL Server 2012 and 2014 in addition to the versions previously listed using varbinary(MAX) columns.
If you are wondering why you cannot "Filestream" (noted in a separate answer) as a datatype in the SQL Server table designer or why you cannot set a column's datatype to "Filestream" using T-SQL, it is because FILESTREAM is a storage attribute of the varbinary(MAX) datatype. It is not a datatype on its own.
See these articles on setting up and enabling FILESTREAM on a database:
https://msdn.microsoft.com/en-us/library/cc645923(v=sql.120).aspx
http://www.kodyaz.com/t-sql/default-filestream-filegroup-is-not-available-in-database.aspx
Once configured, a filestream enabled varbinary(max) column can be added as so:
ALTER TABLE TableName
ADD ColumnName varbinary(max) FILESTREAM NULL
GO
Yes, generally the best way to store a file in a database is to save the byte array in a BLOB column. You will probably want a couple of columns to additionally store the file's metadata such as name, extension, and so on.
It is not always a good idea to store files in the database - for instance, the database size will grow fast if you store files in it. But that all depends on your usage scenario.
Look at this, you may find the answer to your question easier
using:
using System.IO;
using System.Data.SqlClient;
code:
private void Form1_Load(object sender, EventArgs e)
{
display();
}
byte[] filebyte = null;
SqlConnection sqlcon = new SqlConnection("Data Source=.;Initial Catalog=test programin;Integrated Security=True");
SqlCommand sqlcmnd = new SqlCommand();
void display ()
{
DataSet dtset = new DataSet();
SqlDataAdapter sqldta = new SqlDataAdapter("select name from tbl_down_up",sqlcon);
sqldta.Fill(dtset, "tbl_down_up");
dataGridView1.DataSource = dtset;
dataGridView1.DataMember = "tbl_down_up";
dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
private void btnup_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "all file|*.*";
if(ofd.ShowDialog()==DialogResult.OK)
{
FileStream fs = new FileStream(ofd.FileName, FileMode.Open);
MemoryStream ms = new MemoryStream();
fs.CopyTo(ms);
filebyte = ms.ToArray();
string[] filename = ofd.FileName.Split('\\');
sqlcmnd = new SqlCommand("insert into tbl_down_up(name,data)values(#name,#data)",sqlcon);
sqlcmnd.Parameters.AddWithValue("#name",filename[filename.Length-1]);
sqlcmnd.Parameters.AddWithValue("#data",SqlDbType.VarBinary).Value=filebyte;
sqlcon.Open();
sqlcmnd.ExecuteNonQuery();
sqlcon.Close();
sqlcmnd.Parameters.Clear();
display();
}
}
private void btndown_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
string[] filename = dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString().Split('.');
sfd.Filter = "type file " + filename[filename.Length - 1] + " |*." + filename[filename.Length - 1];
sfd.FileName = dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString();
if (sfd.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(sfd.FileName, FileMode.Create);
sqlcmnd = new SqlCommand("select data from tbl_down_up where name ='"+dataGridView1[0,dataGridView1.CurrentRow.Index].Value.ToString()+"'", sqlcon);sqlcon.Open();
SqlDataReader dr = sqlcmnd.ExecuteReader();
while (dr.Read())
{
filebyte = (byte[])dr[0];
}
sqlcon.Close();
fs.Write(filebyte, 0, filebyte.Length);
fs.Close();
display();
}
}
private void btndel_Click(object sender, EventArgs e)
{
sqlcmnd = new SqlCommand("delete from tbl_down_up where name =N'" + dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString() + "'", sqlcon);
sqlcon.Open();
sqlcmnd.ExecuteNonQuery();
sqlcon.Close();
display();
}
video for form:
form1
image for tbl_down_up sqlserver:
tbl_down_up
i can upload images to the database using linq and the listview control when referancing the e.Values method for the ListViewInsertEventArgs, but there is no such method in the ListViewEditEventArgs, so what can i use to achieve the same results?
here is my inserting code:
protected void ProjectPhotosList_ItemInserting(object sender, ListViewInsertEventArgs e)
{
FileUpload uplImage = (FileUpload)ProjectPhotosList.InsertItem.FindControl("uplImage");
Label fileuploadlbl = (Label)ProjectPhotosList.InsertItem.FindControl("fileuploadlbl");
byte[] img = null;
if (uplImage.HasFile || !uplImage.FileName.ToLower().EndsWith(".jpg"))
{
try
{
img = new byte[uplImage.PostedFile.ContentLength];
uplImage.PostedFile.InputStream.Read(img, 0, img.Length);
}
catch
{
fileuploadlbl.Text = "unable to upload " + uplImage.FileName.ToString();
}
}
if (img == null)
{
e.Cancel = true;
fileuploadlbl.Text = "Please choose a file to upload";
}
try
{
e.Values.Add("ProjectPhoto", new System.Data.Linq.Binary(img));
fileuploadlbl.Text = "File Upload Successful";
}
catch
{
fileuploadlbl.Text = "File Upload Failed, please try again";
}
}
ok so i have solved the issue! I just had to go about it a bit of a different way:
this is the important code:
int mykey = int.Parse(ProjectPhotosList.DataKeys[e.ItemIndex].Value.ToString());
its just a simple way to get the primarykey value of the selected row.
I found a post about uploading pdf's to a database and decided to base the rest of my code on that. So here the full code:
protected void ProjectPhotosList_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
FileUpload myFile = (FileUpload)ProjectPhotosList.EditItem.FindControl("uploadImage");
TextBox myCaption = (TextBox)ProjectPhotosList.EditItem.FindControl("ProjectPhotoCaptionTextBox");
int mykey = int.Parse(ProjectPhotosList.DataKeys[e.ItemIndex].Value.ToString());
if (myFile.HasFile)
{
//Get the posted file
Stream fileDataStream = myFile.PostedFile.InputStream;
//Get length of file
int fileLength = myFile.PostedFile.ContentLength;
//Create a byte array with file length
byte[] fileData = new byte[fileLength];
//Read the stream into the byte array
fileDataStream.Read(fileData, 0, fileLength);
//get the file type
string fileType = myFile.PostedFile.ContentType;
//Open Connection
PHJamesDataContext db = new PHJamesDataContext();
//Find the Right Row
PHJProjectPhoto Newphoto = (from p in db.PHJProjectPhotos
where p.ProjectPhotoId == mykey
select p).Single<PHJProjectPhoto>();
Newphoto.ProjectPhoto = fileData;
db.SubmitChanges();
}