Error Trying To Upload Image File In ASP.NET - html

I have the following asp.net C# code to upload an image, and when I try to run it and select the file to upload, it does not recognize that I have selected a file to upload, so I get the message "file not uploaded successfully. I get the following error when trying. Object reference not set to an instance of an object.
I believe I have to add code, to instantiate. I am new to this, and I believe I do not have the correct syntax. I have a data entry form where the File Upload. Can someone tell me what I need, I think I need to add a declaration, as in Line 3 (with ******), but what I have may not be correct if it is not setting the file I am trying to upload, the debugger shows no file, although I am selecting one. Thanks.
See code below
protected void ButImg_Click(object sender, EventArgs e)
{
******FileUpload fileImg = (FileUpload)this.FindControl("fileImg");*****
if (fileImg.HasFile)
{
string imgfile = Path.GetFileName(fileImg.PostedFile.FileName);
string savePath = Path.Combine(ConfigurationManager.AppSettings["ImagesFolder"], imgfile);
fileImg.SaveAs(Server.MapPath("UsrImage/"+ imgfile));
_connstr = System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
/* Save file to Ticket Attachments folder */
if (System.IO.File.Exists(savePath))
{
System.IO.File.Delete(savePath);
}
SqlConnection sqlconn = new SqlConnection(_connstr);
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(_procUpdateImage);
sqlcomm.CommandType = CommandType.StoredProcedure;
sqlcomm.Connection = sqlconn;
sqlcomm.Parameters.AddWithValue("#UsrID", this.txtUsrID.Text);
sqlcomm.Parameters.AddWithValue("#ImageName", imgfile);
sqlcomm.Parameters.AddWithValue("#ImagePath", "Images/" + imgfile);
sqlcomm.Parameters.AddWithValue("#UsrID", _UsrName);
sqlcomm.ExecuteNonQuery();
LitImg.Text = "Image saved successfully";
sqlconn.Close();
fileImg.SaveAs(savePath);
}
else
{
LitImg.Text = "Image not saved successfully";
}
}
.aspx web form for Upload control
<td class="tdSingle">Usr Image</td>
<td class="tdSingle">
<asp:FileUpload ID="fileImg" runat="server"></asp:FileUpload><br/>
<asp:Button ID="ButImg" runat="server" Text="Image Save" OnClick="ButImg_Click" ></asp:Button><br/>
<p>
<asp:Literal ID="LitImg" runat="server"></asp:Literal>
</p>
</td>

Related

MySQL Connector/Net Bulk Uploader not finding file on remote server

I have pored through many pages trying to find an answer but have had no luck. I have a .NET page built in C# that has been working fine until a few days ago. Now it isn't working and I'm pulling my hair out to find out why.
The page has a file uploader that uploads a .csv file and saves it to a folder on the web server. Then it uses the MySQL Bulk Uploader to insert the records into the database on another server.
I have confirmed the file is uploading to the correct folder, but when MySQL tries to insert the records, it fails with the message "File 'E:\inetpub\wwwroot\training\data_uploads\filename.csv' not found (Errcode: 2 - No such file or directory)"
This page has worked for several years without any problem, but I updated some of the NuGet packages and removed some that were not being used, and now it's stopped working. What am I missing? Is there a package or a .dll I need to add back in? Unfortunately, I don't remember what I removed.
Here's the code I'm using:
protected void btnGo_Click(object sender, EventArgs e)
{
try
{
//if file is selected for upload
if (btnSelectFile.HasFile)
{
//upload data file to server
string path = string.Concat(Server.MapPath("~/data_uploads/" + btnSelectFile.FileName));
btnSelectFile.SaveAs(path);
string conString = ConfigurationManager.ConnectionStrings["nameOfConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(conString);
conn.Open();
//get rid of old data
MySqlCommand truncateTerms = new MySqlCommand("TRUNCATE terms_temp;", conn);
truncateTerms.ExecuteNonQuery();
//create bulk uploader and set parameters
var bl = new MySqlBulkLoader(conn);
bl.TableName = "terms_temp";
bl.FieldTerminator = ",";
bl.FieldQuotationCharacter = '"';
bl.LineTerminator = "\r\n";
bl.FileName = path;
bl.NumberOfLinesToSkip = 2;
//insert data
var inserted = bl.Load(); //This is where it fails
conn.Close();
//do some other stuff
catch (Exception ex)
{
Label1.ForeColor = System.Drawing.Color.Red;
Label1.Text = ex.Message.ToString();
}
}
If you're bulk-loading a file that's stored on the web server, not the database server, you need to set MySqlBulkLoader.Local = true, to indicate that the file is local to the database client. Otherwise, the server will give an error that the file isn't found.
For security reasons you will also need to set AllowLoadLocalInfile=true in your connection string to enable this feature.

Flying Saucer - Open an attachment from pdf link

I would like to know if there is a way to create a link (Using HTML) to open an attachment embedded in the pdf document.
Something like this...
Open the attachment file or Open the attachment file
Any suggestion or recommendation?
Thanks
I have been able to implement this scenario after reading the next useful post
https://groups.google.com/forum/#!topic/flying-saucer-users/KuwPoTjaQYU
Steps:
Check out the next repository https://github.com/osnard/flyingsaucer
Analyse the file ITextOutputDevice.java, method processLink(RenderingContext c, Box box)
Make changes based on your needs
Build the project and use the jar file generated
Here the code to create an embedded file based on base64 content.
Java
...String doEmbedFile = handler.getAttributeValue( elem, "data-fs-embed-file" );
if ("true".equals(doEmbedFile.toLowerCase())) {
String fileName = new File(uri).getName();
String content = handler.getAttributeValue( elem, "content" );
com.lowagie.text.Rectangle targetArea = checkLinkArea(c, box);
if (targetArea == null) {
return;
}
try {
if (!_attachments.contains(fileName)) {
byte[] fileBytes = Base64.getDecoder().decode(content.getBytes("UTF-8"));
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(_writer, null, fileName, fileBytes);
fs.addDescription(fileName, true);
_writer.addFileAttachment(fs);
_attachments.add(fileName);
}
targetArea.setBorder(0);
targetArea.setBorderWidth(0);
//This only works on Adobe Acrobat Reader
PdfAction action = PdfAction.javaScript(
"this.exportDataObject({cName:\"" + fileName + "\", nLaunch:2});",
_writer
);...
HTML
<body><div id='div1'><p><a href='test.png' data-fs-embed-file='true' content='iVBORw0KGgoAAAANSUhEU...'>open test.png file</a></p></div><div id='div2'><p><a href='test.pdf' data-fs-embed-file='true' content='JVBERi0xLjUNCiW1tbW1D...'>open test.pdf file</a></p></div><div id='div3'><p><a href='test.txt' data-fs-embed-file='true' content='VEVFRUVFRUVFRVNUIFRYVA=='>open test.txt file</a></p></div></body>
*base64 content truncated
Output
Greetings and I hope it can help others
just open it on new tab, add attribute target="_blank" in your anchor tag
Open attachment

How to download images automatically from database table when it is updated?

I have this sample code to download images from database table manually by clicking a button.
In Html page:
<asp:Button ID="Button1" runat="server" Text="Convert Byte to All Image " OnClick="Button1_Click" />
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
string sConn = ConfigurationManager.ConnectionStrings["conString"].ToString();
SqlConnection objConn = new SqlConnection(sConn);
objConn.Open();
string sTSQL = "Select TOP 1500 FileData, FileValue from Demo_Tbl where Active=1 and FileGroup='C_Photo'";
SqlCommand objCmd = new SqlCommand(sTSQL, objConn);
objCmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable dt = new DataTable();
adapter.SelectCommand = objCmd;
adapter.SelectCommand.CommandTimeout = 10000;
adapter.Fill(dt);
objConn.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
string FileValue = dt.Rows[i]["FileValue"].ToString();
object FileData = dt.Rows[i]["FileData"];
System.IO.File.WriteAllBytes(Server.MapPath("/Images/" + FileValue), (byte[])FileData);
}
Response.Write("Images has been fetched");
}
I want this download to happen automatically when Demo_Tbl table is updated by some one each time. Also I want the download target folder in cloud database(https.clode.azure.com) blobs.
I need some one to help me on this since I'm clue less.
Yeah, its a good idea to download on the update event.
If you write the download code on the update event, it will need to wait the download method before the update event finished. I would recommend you to insert a queue message to Azure storage queue, then use Azure webjob QueueTrigger to download the file to Azure Blob. Here is a similar scenario that use Azure Webjob QueueTrigger to resize the image. I think it will help with your scenario.

Upload a file to Google Drive with embedded browser c#

Since I am unable to capture browser window close event using the GoogleWebAuthorizationBroker.AuthorizeAsync API, I followed this link (http://www.daimto.com/google-api-and-oath2/) to create an embedded browser and authenticate the user. I am unable to continue further to use the access token to upload a file in google drive. Is there any example available to continue from the above link to upload/download a file from Google Drive.
Regards,
Amrut
From the same author, there is a documentation how to upload/ download files to Google Drive.
Like with most of the Google APIs you need to be authenticated in order to connect to them. To do that you must first register your application on Google Developer console. Under APIs be sure to enable the Google Drive API and Google Drive SDK, as always don’t forget to add a product name and email address on the consent screen form.
Make sure your project is at least set to .net 4.0.
Add the following NuGet Package
PM> Install-Package Google.Apis.Drive.v2
In order to download a file we need to know its file resorce the only way to get the file id is from the Files.List() command we used earlier.
public static Boolean downloadFile(DriveService _service, File _fileResource, string _saveTo)
{
if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
{
try
{
var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl );
byte[] arrBytes = x.Result;
System.IO.File.WriteAllBytes(_saveTo, arrBytes);
return true;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return false;
}
}
else
{
// The file doesn't have any content stored on Drive.
return false;
}
}
Using _service.HttpClient.GetByteArrayAsync we can pass it the download url of the file we would like to download. Once the file is download its a simple matter of wright the file to the disk.
Remember from creating a directory in order to upload a file you have to be able to tell Google what its mime-type is. I have a little method here that try’s to figure that out. Just send it the file name. Note: When uploading a file to Google Drive if the name of the file is the same name as a file that is already there. Google Drive just uploads it anyway, the file that was there is not updated you just end up with two files with the same name. It only checks based on the fileId not based upon the file name. If you want to Update a file you need to use the Update command we will check that later.
public static File uploadFile(DriveService _service, string _uploadFile, string _parent) {
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description = "File uploaded by Diamto Drive Sample";
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List() { new ParentReference() { Id = _parent } };
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else {
Console.WriteLine("File does not exist: " + _uploadFile);
return null;
}
}

Best way to turn sql selected data into a table on excel using asp.net

I have an sql statements that selects a table of data that i want to export to excel in the .xls format,
i added this table to a grid view then rendered that grid view to create an html writer and write it on excel file using asp.net.
But i keep having this warning that the file format and extension does not match.
The issue is that the file you are creating is not a genuine Excel file. It's HTML with a .xls extension.
Please, i need to know what is the best way to export these selected data to the xls file without the warning.
I Have also tried exporting from the dataTable directly, but i still get the warning when tying to open the excel.
// these namespaces need to be added to your code behind file
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace MySpot.UserPages
{
public partial class Journal : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MySpotDBConnStr"].ConnectionString);
DataTable dt = new DataTable();
// regular page_load from .aspx file
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
// added a button with ID=btnDownload and double clicked it's onclick event to auto create method
protected void btnDownload_Click(object sender, EventArgs e)
{
string queryStr = "SELECT * from table";
SqlDataAdapter sda = new SqlDataAdapter(queryStr, conn);
sda.Fill(dt);
ExportTableData(dt);
}
// this does all the work to export to excel
public void ExportTableData(DataTable dtdata)
{
string attach = "attachment;filename=journal.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attach);
Response.ContentType = "application/ms-excel";
if (dtdata != null)
{
foreach (DataColumn dc in dtdata.Columns)
{
Response.Write(dc.ColumnName + "\t");
//sep = ";";
}
Response.Write(System.Environment.NewLine);
foreach (DataRow dr in dtdata.Rows)
{
for (int i = 0; i < dtdata.Columns.Count; i++)
{
Response.Write(dr[i].ToString() + "\t");
}
Response.Write("\n");
}
Response.End();
}
}
}
}
http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx
The current design does not allow you to open HTML content from a web site in Excel unless the extension of the URL is .HTM/.HTML/.MHT/.MHTML. So ASP pages that return HTML and set the MIME type to something like XLS to try to force the HTML to open in Excel instead of the web browser (as expected) will always get the security alert since the content does not match the MIME type. If you use an HTML MIME type, then the web browser will open the content instead of Excel. So there is no good workaround for this case because of the lack of a special MIME type for HTML/MHTML that is Excel specific. You can add your own MIME type if you control both the web server and the client desktops that need access to it, but otherwise the best option is to use a different file format or alert your users of the warning and tell them to select Yes to the dialog.