• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 477
  • Last Modified:

File Upload Facility

Hi i am working on an application in classic asp and would like to include a picture upload facility (the server supports .net applications too)  I have this code below working on the server and it will upload the files to the directory specied in the sSavePath, however i need a line adding into the DB table with the product ID and also the image name...

If we take this step by step then..

1) My ASP page passes a querystring to the upload.aspx page so it says .../upload.aspx?ProductID=16
2) How do i get the querystring ProductID into the code
3) How do i then add a record into the tblImages table populating the fields...  intProductID / txtImageName / txtThumbnailName

The code i have below fails with Compilation Error - Compiler Error Message: CS0118: 'System.Web.HttpRequest.QueryString' denotes a 'property' where a 'method' was expected

Source error Line 13: sQueryString = Request.QueryString("ProductID");

Any Ideas!? I am new to ASP.net so go easy on me!!!

Cheers,
Carl

*************************************CODE START***********************************************
<%@ Page Language="c#" Debug="true" %>
<script runat="server">

    void btnUpload_Click(object sender, EventArgs e) {
    // Initialize variables
        string sSavePath;
        string sThumbExtension;
        string sQueryString;
        int intThumbWidth;
        int intThumbHeight;
   
        // Set constant values
        sQueryString = Request.QueryString("ProductID");
        sSavePath = "/includes/pages/retail/products/product_images/";
        sThumbExtension = "_thumb";
        intThumbWidth = 160;
        intThumbHeight = 120;
   
        // If file field isn’t empty
        if (filUpload.PostedFile != null)
        {
            // Check file size (mustn’t be 0)
            HttpPostedFile myFile = filUpload.PostedFile;
            int nFileLen = myFile.ContentLength;
            if (nFileLen == 0)
            {
                lblOutput.Text = "No file was uploaded.";
                return;
            }
   
            // Check file extension (must be JPG)
            if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
            {
                lblOutput.Text = "The file must have an extension of JPG";
                return;
            }
   
            // Read file into a data stream
            byte[] myData = new Byte[nFileLen];
            myFile.InputStream.Read(myData,0,nFileLen);
   
            // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an
            // incremental numeric until it is unique
            string sFilename = System.IO.Path.GetFileName(myFile.FileName);
            int file_append = 0;
            while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
            {
                file_append++;
                sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                 + file_append.ToString() + ".jpg";
            }
   
            // Save the stream to disk
            System.IO.FileStream newFile
                    = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
                                               System.IO.FileMode.Create);
            newFile.Write(myData,0, myData.Length);
            newFile.Close();
   
            // Check whether the file is really a JPEG by opening it
            System.Drawing.Image.GetThumbnailImageAbort myCallBack =
                           new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            System.Drawing.Bitmap myBitmap;
            try
            {
                myBitmap = new System.Drawing.Bitmap(Server.MapPath(sSavePath + sFilename));
   
                // If jpg file is a jpeg, create a thumbnail filename that is unique.
                file_append = 0;
                string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                                         + sThumbExtension + ".jpg";
                while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
                {
                    file_append++;
                    sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
                                   file_append.ToString() + sThumbExtension + ".jpg";
                }
   
                // Save thumbnail and output it onto the webpage
                System.Drawing.Image myThumbnail
                        = myBitmap.GetThumbnailImage(intThumbWidth,
                                                     intThumbHeight, myCallBack, IntPtr.Zero);
                myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile));
                imgPicture.ImageUrl = sSavePath + sThumbFile;
   
                // Displaying success information
                lblOutput.Text = "File uploaded successfully!";
                lblOutput.Text = sQueryString;
   
                // Destroy objects
                myThumbnail.Dispose();
                myBitmap.Dispose();
            }
            catch (ArgumentException errArgument)
            {
                // The file wasn't a valid jpg file
                lblOutput.Text = "The file wasn't a valid jpg file.";
                System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
            }
        }
    }
   
    public bool ThumbnailCallback()
    {
        return false;
    }

</script>

<html>
<head>
</head>
<body>
    <form enctype="multipart/form-data" runat="server">
        <p>
            <input id="filUpload" type="file" runat="server" />
        </p>
        <p>
        </p>
        <p>
            <asp:Button id="btnUpload" onclick="btnUpload_Click" runat="server" Text="Button"></asp:Button>
        </p>
        <p>
            <asp:Label id="lblOutput" runat="server">Label</asp:Label>
            <asp:Label id="lblQueryString" runat="server">Label</asp:Label>
        </p>
        <p>
            <asp:Image id="imgPicture" runat="server" height="120" width="160"></asp:Image>
        </p>
        <!-- Insert content here -->
    </form>
</body>
</html>
*************************************CODE END***********************************************
0
net-workx
Asked:
net-workx
  • 5
  • 4
1 Solution
 
GavinMannionCommented:
Okay you are using C# so instead of

Request.QueryString("ProductId")

You need

Request.QueryString["ProductID"]

For the database side do you have any knowledge of reading and writing from the database?

You need to instantiate a SqlConnection and SqlCommand and then execute a stored procedure through that.

SqlConnection myConnection = new SqlConnection;
myConnection.ConnectionString = "";
SqlCommand myCommand = new SqlCommand("StoredProcedureName");
myCommand.Connection = myConnection;
myCommand.Parameters.Add("@FileName", fileName);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
0
 
net-workxAuthor Commented:
Right got it to change the text box to the ProductID from the querystring like you told me.

As regards the DB - have know knowledge of how to get this working from ASP.net

In asp i would write something like...

<%
intProductID = Request.QueryString("ProductID")

DSN = "DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" & Server.Mappath("/db/retailer_database.mdb") & ";"
Set Connection = Server.CreateObject("ADODB.Connection")
Connection.Open(DSN)

Set RS = Server.CreateObject("ADODB.Recordset")
SQL = "SELECT * FROM tblProductImages WHERE ID = 0"
RS.Open SQL,Connection,3,3

RS.AddNew

RS.Fields("intProductID") = intProductID
RS.Fields("txtImageName") = Request.Form("txtImageName")
RS.Fields("txtThumbnailName") = Request.Form("txtThumbnailName")

RS.Update

RS.Close
Set RS = Nothing
Connection.Close
Set Connection = Nothing

Response.Redirect "/page.asp?PageID=NewProduct&Confirmation=1"
%>

Any idea of how this would translate into ASP.net?

Thanks,
Carl
0
 
GavinMannionCommented:
hmm I don't use Access much but I would think you would just change the code I wrote slightly to look more like

OleDBConnection myConnection = new OleDBConnection;
myConnection.ConnectionString = "";
OleDBCommand myCommand = new OleDBCommand();
myCommand.CommandText = "INSERT INTO tblProductImages (intProductID, txtImageName, txtThumbNailName) VALUES (" + intProductID + ", #" + Request.Form("txtImageName") + "#, #" Request.Form("txtThumbNailName")  "#";
myCommand.Connection = myConnection;
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();

However if your textboxes are set to runat="server" then instead of Request.Form change it to txtImageName.Text to get the value of the textbox.

Make sure you are using the following two at the top of the class
using System.Data;
using System.Data.OleDb;
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
net-workxAuthor Commented:
Ok i wasnt really clear on that one....

What i need to do in the script i posted is get the filename, the thumbnail name and the productID from the upload facility then add a record into the DB with it?

Not sure where to start to get the actual filename from the upload form?

Cheers
Carl
0
 
GavinMannionCommented:
To get the filename

filUpload.Text

The rest you setup yourself so just make them a public variable and you should be able to use that straight.
Else put them in Sessions and get them from there.
0
 
net-workxAuthor Commented:
ok i have progressed a bit to this...

<%@ Page Language="c#" %>
<script runat="server">

    int insert(int intProductID, string txtImageName, string txtThumbnailName) {
            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=C:\\inetpub\\wwwroot\\ad" +
    "min\\db\\live_poundgland.mdb";
            System.Data.IDbConnection dbConnection = new System.Data.OleDb.OleDbConnection(connectionString);
   
            string queryString = "INSERT INTO [tblProductImages] ([intProductID], [txtImageName], [txtThumbnailName" +
    "]) VALUES (@intProductID, @txtImageName, @txtThumbnailName)";
            System.Data.IDbCommand dbCommand = new System.Data.OleDb.OleDbCommand();
            dbCommand.CommandText = queryString;
            dbCommand.Connection = dbConnection;
   
            System.Data.IDataParameter dbParam_intProductID = new System.Data.OleDb.OleDbParameter();
            dbParam_intProductID.ParameterName = "@intProductID";
            dbParam_intProductID.Value = intProductID;
            dbParam_intProductID.DbType = System.Data.DbType.Int32;
            dbCommand.Parameters.Add(dbParam_intProductID);
            System.Data.IDataParameter dbParam_txtImageName = new System.Data.OleDb.OleDbParameter();
            dbParam_txtImageName.ParameterName = "@txtImageName";
            dbParam_txtImageName.Value = txtImageName;
            dbParam_txtImageName.DbType = System.Data.DbType.String;
            dbCommand.Parameters.Add(dbParam_txtImageName);
            System.Data.IDataParameter dbParam_txtThumbnailName = new System.Data.OleDb.OleDbParameter();
            dbParam_txtThumbnailName.ParameterName = "@txtThumbnailName";
            dbParam_txtThumbnailName.Value = txtThumbnailName;
            dbParam_txtThumbnailName.DbType = System.Data.DbType.String;
            dbCommand.Parameters.Add(dbParam_txtThumbnailName);
   
            int rowsAffected = 0;
            dbConnection.Open();
            try {
                rowsAffected = dbCommand.ExecuteNonQuery();
            }
            finally {
                dbConnection.Close();
            }
   
            return rowsAffected;
        }
    void btnUpload_Click(object sender, EventArgs e) {
    // Initialize variables
        string sSavePath;
        string sThumbExtension;
        string sQueryString;
        int intThumbWidth;
        int intThumbHeight;
   
        // Set constant values
        sQueryString = Request.QueryString["ProductID"];
        sSavePath = "/admin/includes/pages/retail/products/product_images/";
        sThumbExtension = "_thumb";
        intThumbWidth = 160;
        intThumbHeight = 120;
   
        // If file field isn’t empty
        if (filUpload.PostedFile != null)
        {
            // Check file size (mustn’t be 0)
            HttpPostedFile myFile = filUpload.PostedFile;
            int nFileLen = myFile.ContentLength;
            if (nFileLen == 0)
            {
                lblOutput.Text = "No file was uploaded.";
                return;
            }
   
            // Check file extension (must be JPG)
            if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
            {
                lblOutput.Text = "The file must have an extension of JPG";
                return;
            }
   
            // Read file into a data stream
            byte[] myData = new Byte[nFileLen];
            myFile.InputStream.Read(myData,0,nFileLen);
   
            // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an
            // incremental numeric until it is unique
            string sFilename = System.IO.Path.GetFileName(myFile.FileName);
            int file_append = 0;
            while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
            {
                file_append++;
                sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                 + file_append.ToString() + ".jpg";
            }
   
            // Save the stream to disk
            System.IO.FileStream newFile
                    = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
                                               System.IO.FileMode.Create);
            newFile.Write(myData,0, myData.Length);
            newFile.Close();
   
            // Check whether the file is really a JPEG by opening it
            System.Drawing.Image.GetThumbnailImageAbort myCallBack =
                           new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            System.Drawing.Bitmap myBitmap;
            try
            {
                myBitmap = new System.Drawing.Bitmap(Server.MapPath(sSavePath + sFilename));
   
                // If jpg file is a jpeg, create a thumbnail filename that is unique.
                file_append = 0;
                string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                                         + sThumbExtension + ".jpg";
                while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
                {
                    file_append++;
                    sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
                                   file_append.ToString() + sThumbExtension + ".jpg";
                }
   
                // Save thumbnail and output it onto the webpage
                System.Drawing.Image myThumbnail
                        = myBitmap.GetThumbnailImage(intThumbWidth,
                                                     intThumbHeight, myCallBack, IntPtr.Zero);
                myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile));
                imgPicture.ImageUrl = sSavePath + sThumbFile;
   
                // Displaying success information
                lblOutput.Text = "File uploaded successfully!";
   
                // Destroy objects
                myThumbnail.Dispose();
                myBitmap.Dispose();
                 insert( sQueryString,myFile.FileName);
            }
            catch (ArgumentException errArgument)
            {
                // The file wasn't a valid jpg file
                lblOutput.Text = "The file wasn't a valid jpg file.";
                System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
            }
   
   
   
        }
    }
   
    public bool ThumbnailCallback()
    {
        return false;
    }

</script>
<html>
<head>
</head>
<body>
    <form enctype="multipart/form-data" runat="server">
        <p>
            <input id="filUpload" type="file" runat="server" />
        </p>
        <p>
        </p>
        <p>
            <asp:Button id="btnUpload" onclick="btnUpload_Click" runat="server" Text="Upload Now"></asp:Button>
        </p>
        <p>
            <asp:Label id="lblOutput" runat="server"> </asp:Label>
        </p>
        <p>
            <asp:Image id="imgPicture" runat="server" width="160" height="120"></asp:Image>
        </p>
        <!-- Insert content here -->
    </form>
</body>
</html>

but i have error now saying...

Line 130: insert( sQueryString,myFile.FileName);

CS1501: No Overload For method 'insert' takes '2' arguments

Any Ideas?
Carl
0
 
GavinMannionCommented:
Basically as it says, your method insert is expecting 3 arguments... You defined it at the top

int insert(int intProductID, string txtImageName, string txtThumbnailName)

You are only send 2... If the last one is unimportant change line 130 to look like

insert( sQueryString,myFile.FileName,"");

0
 
net-workxAuthor Commented:
Job done!  Its all working now, thanks for your help..


Finished code looks like this...

<%@ Page Language="c#" Debug="true" %>
<script runat="server">

    int insert(int intProductID, string txtImageName) {
            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=C:\\inetpub\\wwwroot\\ad" +
    "min\\db\\live_poundgland.mdb";
            System.Data.IDbConnection dbConnection = new System.Data.OleDb.OleDbConnection(connectionString);
   
            string queryString = "INSERT INTO [tblProductImages] ([intProductID], [txtImageName])" +
    "VALUES (@intProductID, @txtImageName)";
            System.Data.IDbCommand dbCommand = new System.Data.OleDb.OleDbCommand();
            dbCommand.CommandText = queryString;
            dbCommand.Connection = dbConnection;
   
            System.Data.IDataParameter dbParam_intProductID = new System.Data.OleDb.OleDbParameter();
            dbParam_intProductID.ParameterName = "@intProductID";
            dbParam_intProductID.Value = intProductID;
            dbParam_intProductID.DbType = System.Data.DbType.Int32;
            dbCommand.Parameters.Add(dbParam_intProductID);
            System.Data.IDataParameter dbParam_txtImageName = new System.Data.OleDb.OleDbParameter();
            dbParam_txtImageName.ParameterName = "@txtImageName";
            dbParam_txtImageName.Value = txtImageName;
            dbParam_txtImageName.DbType = System.Data.DbType.String;
            dbCommand.Parameters.Add(dbParam_txtImageName);
   
            int rowsAffected = 0;
            dbConnection.Open();
            try {
                rowsAffected = dbCommand.ExecuteNonQuery();
            }
            finally {
                dbConnection.Close();
            }
   
            return rowsAffected;
        }
    void btnUpload_Click(object sender, EventArgs e) {
    // Initialize variables
        string sSavePath;
        string sThumbExtension;
        string sQueryString;
        int intThumbWidth;
        int intThumbHeight;
   
        // Set constant values
        sQueryString  = Request.QueryString["ProductID"];
        sSavePath = "/admin/includes/pages/retail/products/product_images/";
        sThumbExtension = "_thumb";
        intThumbWidth = 160;
        intThumbHeight = 120;
   
        // If file field isn’t empty
        if (filUpload.PostedFile != null)
        {
            // Check file size (mustn’t be 0)
            HttpPostedFile myFile = filUpload.PostedFile;
            int nFileLen = myFile.ContentLength;
            if (nFileLen == 0)
            {
                lblOutput.Text = "No file was uploaded.";
                return;
            }
   
            // Check file extension (must be JPG)
            if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
            {
                lblOutput.Text = "The file must have an extension of JPG";
                return;
            }
   
            // Read file into a data stream
            byte[] myData = new Byte[nFileLen];
            myFile.InputStream.Read(myData,0,nFileLen);
   
            // Make sure a duplicate file doesn’t exist.  If it does, keep on appending an
            // incremental numeric until it is unique
            string sFilename = System.IO.Path.GetFileName(myFile.FileName);
            int file_append = 0;
            while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
            {
                file_append++;
                sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                 + file_append.ToString() + ".jpg";
            }
   
            // Save the stream to disk
            System.IO.FileStream newFile
                    = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
                                               System.IO.FileMode.Create);
            newFile.Write(myData,0, myData.Length);
            newFile.Close();
   
            // Check whether the file is really a JPEG by opening it
            System.Drawing.Image.GetThumbnailImageAbort myCallBack =
                           new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            System.Drawing.Bitmap myBitmap;
            try
            {
                myBitmap = new System.Drawing.Bitmap(Server.MapPath(sSavePath + sFilename));
   
                // If jpg file is a jpeg, create a thumbnail filename that is unique.
                file_append = 0;
                string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                                         + sThumbExtension + ".jpg";
                while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
                {
                    file_append++;
                    sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
                                   file_append.ToString() + sThumbExtension + ".jpg";
                }
   
                // Save thumbnail and output it onto the webpage
                System.Drawing.Image myThumbnail
                        = myBitmap.GetThumbnailImage(intThumbWidth,
                                                     intThumbHeight, myCallBack, IntPtr.Zero);
                myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile));
                imgPicture.ImageUrl = sSavePath + sThumbFile;
   
                // Displaying success information
                lblOutput.Text = "File uploaded successfully!";
   
                // Destroy objects
                myThumbnail.Dispose();
                myBitmap.Dispose();
                 insert( Convert.ToInt32(sQueryString),sFilename);
            }
            catch (ArgumentException errArgument)
            {
                // The file wasn't a valid jpg file
                lblOutput.Text = "The file wasn't a valid jpg file.";
                System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
            }
   
   
   
        }
    }
   
    public bool ThumbnailCallback()
    {
        return false;
    }

</script>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
    <form enctype="multipart/form-data" runat="server">
        <p>
            <input id="filUpload" type="file" runat="server" />
        </p>
        <p>
        </p>
        <p>
            <asp:Button id="btnUpload" onclick="btnUpload_Click" runat="server" Text="Upload Now"></asp:Button>
        </p>
        <p>
            <asp:Label id="lblOutput" runat="server"> </asp:Label>
        </p>
        <p>
            <asp:Image id="imgPicture" runat="server" height="120" width="160"></asp:Image>
        </p>
        <!-- Insert content here -->
    </form>
</body>
</html>
0
 
GavinMannionCommented:
Great glad to hear it is working.

I just wish my other question was progressing as well :)

If you can help please feel free to jump in

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP_DOT_NET/Q_21820244.html
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now