|
I had the same problem. It seems you need to tell .net the type of image file it is when you're saving the thumbnail. See code below:
//Put these classes at the tip of your class file
//I don't like writing these out all throughout the code
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
//Put this code at the top of the button click event
//initialize the type variable
ImageFormat imgFrmt = null;
//I replaced his check for a valid jpg with a check for gif, jpg or png
if (imgFile.ContentType != "image/pjpeg" && imgFile.ContentType != "image/gif" && imgFile.ContentType != "image/x-png")
{
lblOutput.Text = "The file must have an extension of JPG,GIF or PNG";
return;
}
//Put the code below in just before you try to save myThumbnail
//I added more code to his example to handle more image types so I have a
//switch to determine which format this file is in
//If you're only using one type, you could just initialize the variable
//above something like (ImageFormat imgFrmt = ImageFormat.Jpeg;)
switch(Convert.ToString(Path.GetExtension(imgFile.FileName)).ToLower())
{
case ".gif":
imgFrmt = ImageFormat.Gif;
break;
case ".jpeg":
case ".jpg":
imgFrmt = ImageFormat.Jpeg;
break;
case ".png":
imgFrmt = ImageFormat.Png;
break;
} //end switch
//Now when you use his code to save the image
//add the format parameter "imgFrmt" to it:
myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile), imgFrmt);
Charles T.
|
|
|
|
|
Not sure if this is a useful shortcut, or if I'm going to cause myself a lot of hassle later, but I did the following:-
First, I checked the mime-type to ensure the file was a JPG/GIF/PNG - I figure this is more fool-proof than just checking the extension.
Then, instead of saving the file and then opening the file up into the bitmap, I read the InputStream directly into a new Bitmap:-
Bitmap objBitmap = new Bitmap(myFile.InputStream);
From here, I can check the dimensions of the image, determine if I need to create a thumbnail (or if the image is small enough to act as its own), etc. You can use Bitmap.Save(..) to store the image - if storing to a DB Blob, I'm guessing you could either Read the Stream first into a Byte[] array, or write the Bitmap into the Blob.
So far, I haven't had any problems with this, but if there is something I've missed I'm sure one of you will know.
Two areas I'll like to sort out:-
A) Is there a better way to generate a unique filename? (they don't have to be user-friendly, since the user-friendly name is stored in the database, with its associated unique filename)
B) when sending the image back to the browser (I'm using a GetImage.aspx?user=2&img=3 setup), can I attach the user-friendly name to the image - for example if they right-click and Save Picture As... the filename in the 'Save As' dialog would be the user-friendly name stored in the database.
Yours,
Ann-Marie Ratcliffe
|
|
|
|
|
Is there any article on retrieving files from database where user had uploaded earlier?
|
|
|
|
|
Introduction
This article describes how to upload images to a web server using ASP.NET. All the data is stored in a MySQL database. This article is targeted towards a little more intermediate programmer who has some understanding of ASP.NET with C#, SQL and relational databases. First section describes how to set up the database and second part describes how to code uploading the files and how to view them back as a gallery. Code has been tested with JPEG and GIF files.
Setting Up the Database
The database that I have used is MySQL. Information on how to obtain and install MySQL can be obtained from here. To make the process of creation and interacting with the database, I used MySQL control center. This allows a visual way for creating and interacting with a MySQL database.
MySQL comes with a default database called test. And I will be using this database.
The next thing is to create a table called file with the following columns.
ID – Select it to be a timestamp to create it as the primary key of the table.
Extension – Select it as varchar.
Data – Select it as longblob.
To connect to the MySQL database, MySQL ODBC driver has to be downloaded. The version of MySQL ODBC driver is 3.51 that I have used for this article. All the code to interact with database is placed in a DataAccess class.
public class DataAccess
{
private string _strConn =
@"Driver= {MySQLODBC 3.51 Driver};SERVER=localhost;DATABASE=test;";
private OdbcConnection _objConn;
public DataAccess()
{
this._objConn = new OdbcConnection(this._strConn);
}
// This function adds the Images to database
public string addImage(byte [] buffer,string extension)
{
string strSql = "SELECT * FROM File";
DataSet ds = new DataSet("Image");
OdbcDataAdapter tempAP = new OdbcDataAdapter(strSql,this._objConn);
OdbcCommandBuilder objCommand = new OdbcCommandBuilder(tempAP);
tempAP.Fill(ds,"Table");
try
{
this._objConn.Open();
DataRow objNewRow = ds.Tables["Table"].NewRow();
objNewRow["Extension"] = extension;
objNewRow["Data"] = buffer;
ds.Tables["Table"].Rows.Add(objNewRow);
// trying to update the table to add the image
tempAP.Update(ds,"Table");
}
catch(Exception e){return e.Message;}
finally{this._objConn.Close();}
return null;
}
// This function to get the image data from the database
public byte [] getImage(int imageNumber)
{
string strSql = "SELECT * FROM File";
DataSet ds = new DataSet("Image");
OdbcDataAdapter tempAP = new OdbcDataAdapter(strSql,this._objConn);
OdbcCommandBuilder objCommand = new OdbcCommandBuilder(tempAP);
tempAP.Fill(ds,"Table");
try
{
this._objConn.Open();
byte [] buffer = (byte [])ds.Tables["Table"].Rows[imageNumber]["Data"];
return buffer;
}
catch{this._objConn.Close();return null;}
finally{this._objConn.Close();}
}
// Get the image count
public int getCount()
{
string strSql = "SELECT COUNT(Data) FROM File";
DataSet ds = new DataSet("Image");
OdbcDataAdapter tempAP = new OdbcDataAdapter(strSql,this._objConn);
OdbcCommandBuilder objCommand = new OdbcCommandBuilder(tempAP);
tempAP.Fill(ds,"Table");
try>
{
this._objConn.Open();
int count = (int)ds.Tables["Table"].Rows[0][0];
return count;
}
catch{this._objConn.Close();return 0;}
finally{this._objConn.Close();}
}
}
Getting the User Uploaded files
To upload the files to the web server, a very simple ASP.NET web form is used, which is composed of a file field and a submit button. The Web form file in the project is Upload.aspx and the code is place in Upload.aspx.cs. The file is obtained and put in the database in the Page_Load function. Now the code takes a look into the Request.Files collection. As the interface allows to upload only one file, therefore, we check it if there is a file pending on IIS. The code checks for the mime type of the file if it is an image it accepts, otherwise it just displays a message that mime type is not supported. If the file is an image, data is read in bytes and inserted into the MySQL database using the DataAccess class object.
private void Page_Load(object sender, System.EventArgs e)
{
//Checking if there are any files avaiable on IIS.
if(Request.Files.Count != 0)
{
HttpPostedFile httpFile = Request.Files[0];
// Checking for extension
string extension = this.getFileExtension(httpFile.ContentType);
if(extension == null )
{
Response.Write("Mime type not Supported");
return;
}
System.IO.BufferedStream bf = new BufferedStream(httpFile.InputStream);
byte[] buffer = new byte[bf.Length];
bf.Read(buffer,0,buffer.Length);
// Creating the database object
DataAccess data = new DataAccess();
// Adding files to the database.
data.addImage(buffer,extension);
Response.Write("Image Added!");
}
}
Displaying Upload File
Now, to display the uploaded files for the user, another Web form is setup in a file called View.aspx. Getting the image data is done by another file called show.aspx.
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
Data.DataAccess data = new Data.DataAccess();
int imagenumber = 0;
try
{
imagenumber = int.Parse(Request.QueryString["image"]);
}
catch(System.ArgumentNullException ee)
{
imagenumber = 0;
}
byte [] buffer = data.getImage(imagenumber);
System.IO.MemoryStream stream1 = new System.IO.MemoryStream(buffer,true);
stream1.Write(buffer,0,buffer.Length);
Bitmap m_bitmap = (Bitmap) Bitmap.FromStream(stream1,true);
Response.ContentType = "Image/jpeg";
m_bitmap.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
}
View.aspx allows the user to go to the next file by clicking next link.
hello...This is sandeep vyas, software developer in pune and i wanna join code project
|
|
|
|
|
I m using the Microsoft ASP.NET Web Matrix right now doing the uploading codes, but seeme like i can't get it done easily.
I encountered the followings problem:
1) i follow the steps and paste in the whole codes, the error message that turns back is
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: BC30205: End of statement expected.
Source Error:
Line 2:
Line 3:
Line 4: private void btnUpload_Click(object sender, System.EventArgs e)
Line 5: {
Line 6: // Initialize variables
The line4 is the problem, it needs a end statement... I juz started to learn programming and asp.net recently so i really don't what to do.
Please help !!!
How shall the whole codings look like after the whole thing is fix generally? I really like to take a look.
Don't Worry, Be Happy !!!
|
|
|
|
|
Try editing Line 2 to:-
<script language="c#" runat="server">
I think its trying to read the script as VB.NET.
HTH,
Ann-Marie Ratcliffe
|
|
|
|
|
Hi,
According to this example it will stored the both thumbnail image and original image that is posted from client mechine .
but i don't want to save the original image that is posted from the client mechine into server, what i want is to save only the thumbnail image insted of original image file.can any one help me regarding this issue
|
|
|
|
|
Nice article only if you want a file to upload wich aint a jpg you can just change the extention to jpg and it will upload.
Better method is to check on ContentType. So it would be:
if(Upload.PostedFile.ContentType == "image/pjpeg")
some contenttypes:
jpg = image/pjpeg
gif = image/gif
png = image/x-png
|
|
|
|
|
I think using htmlInputFile is simpler :
But i don't know how i can upload a file in my code only without add a htmlInputFile control to my Webform. Help me !
The following example demonstrates how to use the PostedFile property to initiate the utility that transfers the file to the server.
[Visual Basic]
<%@ Page Language="VB" AutoEventWireup="True" %>
Sub Button1_Click(Source As Object, e As EventArgs)
If Text1.Value = "" Then
Span1.InnerHtml = "Error: you must enter a file name"
Return
End If
If Not (File1.PostedFile Is Nothing) Then
Try
File1.PostedFile.SaveAs(("c:\temp\" & Text1.Value))
Span1.InnerHtml = "File uploaded successfully to <b>c:\temp\" & _
Text1.Value & "</b> on the Web server"
Catch exc As Exception
Span1.InnerHtml = "Error saving file <b>c:\temp\" & _
Text1.Value & "</b><br>" & exc.ToString()
End Try
End If
End Sub 'Button1_Click
HtmlInputFile Sample
Select File to Upload:
Save as filename (no path):
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
void Button1_Click(object Source, EventArgs e)
{
if (Text1.Value == "")
{
Span1.InnerHtml = "Error: you must enter a file name";
return;
}
if (File1.PostedFile != null)
{
try
{
File1.PostedFile.SaveAs("c:\\temp\\"+Text1.Value);
Span1.InnerHtml = "File uploaded successfully to <b>c:\\temp\\" +
Text1.Value + "</b> on the Web server";
}
catch (Exception exc)
{
Span1.InnerHtml = "Error saving file <b>c:\\temp\\" +
Text1.Value + "</b><br>" + exc.ToString();
}
}
}
HtmlInputFile Sample
Select File to Upload:
Save as filename (no path):
cuonglt
|
|
|
|
|
How can I overcome this problem??
I'm using WinXP,IIS 5.0, .NET 2002
10x
Yariv.
|
|
|
|
|
I also have this problem.
Has anyone seen it? How did you solve it?
Thanks.
|
|
|
|
|
Hi, I had this problem too. The solution that worked for me was giving the guest internet account full access to the folder, you should be OK with this as long as you make sure people are just uploading JPEGs! Right click on the folder in question, select Properties and you get this dialog ...
these are the output images from the script ... php doesn't like the thumbnails for some reason :-/
http://yay.realmaracuja.com/index.php?filePath=/My%20DotNet%20Uploader%20Test/
|
|
|
|
|
HI!
even i am getting the same problem,pls could u explain what do u mean by full access and how to change these properties.
SAM
|
|
|
|
|
I had the same error . No need to use Guest , just ensure that ASP-NET ( Duh!) has Write access to the folder by default it does not.
Ben
|
|
|
|
|
This worked like a charm! Thanks for the article!
Wally Atkins Newport News, VA, USA
|
|
|
|
|
I can’t find a reference to this and neither can the compiler I get an error and to tell the truth I don’t even know what it is doing. Its line 66 and 67 in this article if anyone can help I would appreciate it.
Thanks
|
|
|
|
|
|
Hi Chris,
I would like to know if you are able the upload the jpg image and resize it without decompressing it and therefore not having to recompress it. Image quality is important to me and I notice that after each image goes through the upload process it looses quality.
I would also then like to rotate the image but because of the above problem have found the resulting image quality unacceptable
I believe there are algorithms that can do this but as yet have had no success finding one.
thanks for any help
Evan
|
|
|
|
|
I am currently looking for asp.net programmer's help, you might be interested in this project..
Please go to www.amodesign.com to see the detail discription..
have a great day...
~Amo
|
|
|
|
|
As i can see, it seems that it´s a little bit complex to get the script run on my server.
I´ve uploaded the to files, but it seems so, that I need some mor files on the server?!
for example: netimageupload.WebForm1 ??? or some classes?
Whre did i get them and where must i install these files?
|
|
|
|
|
i entered the code into Microsoft's new web matrix editor and got
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1513: } expected
Source Error:
Line 100: }
Line 101: }
Line 102: }
Line 103:
Line 104: public bool ThumbnailCallback()
whats the deal? I tried placing }'s all around the error to no avail.... I am stuck...
|
|
|
|
|
Hi,
i´ve uploaded your code upload.aspx. But there is a server error:
Parser Error Message: Could not load type 'netimageupload.WebForm1'.
Source Error:
Line 1: <%@ Page language="c#" Codebehind="upload.aspx.cs" AutoEventWireup="false" Inherits="netimageupload.WebForm1" %>
Line 2:
Line 3:
What does it mean. Whre can i find the 'netimageupload.WebForm1'. And where must it be installed???
Kupfernagel@ludwig-hoehne.de
|
|
|
|
|
hi
i too faced same prob.
please include Src="upload.aspx.cs"
<%@ Page language="c#" Codebehind="upload.aspx.cs" AutoEventWireup="false" Inherits="netimageupload.WebForm1" Src="upload.aspx.cs"%>
thanks
prem
Premnath Ghawalkar
14082428974
|
|
|
|
|
you need to replace netimageupload with whatever you named you project and WebForm1 with whatever you named your form.
|
|
|
|
|
What do you meen by "named your project"?
Thanks,
Jordan
|
|
|
|