Is the code for uploading multiple images not functioning as expected?

My Photo Table is

Column Name Data Type   Constraint
PhotoID     Int         Primary key,auto increment
PhotoName   Varchar(100)    
ExtName     Varchar(100)    
PhotoType   Varchar(100)    
PhotoSize   Int 
TempleID    Int         Foreign key with templeinfo

and the insertion procedure is as follows:

create proc [dbo].[prcTemplePhoto]
(
@PhotoName  Varchar(100),
@ExtName    Varchar(100),
@PhotoType  Varchar(100),
@PhotoSize  int,
@TempleID   Int
)
as
insert into TemplePhoto(PhotoName,ExtName,PhotoType,PhotoSize,TempleID) values (@PhotoName,@ExtName,@PhotoType,@PhotoSize,@TempleID)
select @@IDENTITY

In order to upload multiple photos at once, I found a code snippet online that I incorporated into my design:

On the design side:

<tr>
        <td>
            <asp:Label ID="lbltemplepic" runat="server" Text="Temple Photo"></asp:Label>
        </td>
        <td id="fileUploadarea">
            <div>
                <div id="Div1">
                    <asp:FileUpload ID="templeupload" runat="server" CssClass="fileUpload" /><br />
                </div>
                <br />
                <div>
                    <input style="display: block;" id="btnAddMoreFiles" type="button" value="Add more images" onclick="AddMoreImages();" /><br />
                    <asp:Button ID="btnuplaod" runat="server"  Text="Upload" OnClick="btnuplaod_Click"  />
                </div>
            </div>
        </td>
        <td></td>
    </tr>
<tr><td></td><td>
    <asp:Button ID="btninsert" runat="server" Text="Insert" OnClick="btninsert_Click"  />
    </td><td></td></tr>
    <tr><td></td><td>
        <asp:Label ID="lblerror" runat="server" Text=""></asp:Label></td><td></td></tr>
                   <script lang="javascript" type="text/javascript">
                       function AddMoreImages() {
                           if (!document.getElementById && !document.createElement)
                               return false;
                           var fileUploadarea = document.getElementById("fileUploadarea");
                           if (!fileUploadarea)
                               return false;
                           var newLine = document.createElement("br");
                           fileUploadarea.appendChild(newLine);
                           var newFile = document.createElement("input");
                           newFile.type = "file";
                           newFile.setAttribute("class", "fileUpload");

                           if (!AddMoreImages.lastAssignedId)
                               AddMoreImages.lastAssignedId = 100;
                           newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
                           newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
                           var div = document.createElement("div");
                           div.appendChild(newFile);
                           div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
                           fileUploadarea.appendChild(div);
                           AddMoreImages.lastAssignedId++;
                       }
                       </script>

And on the code side:

 if (templeupload.HasFile)
                {
                    TemplePhoto tempphoto = new TemplePhoto();
                    tempphoto.PhotoName = templeupload.FileName;
                    tempphoto.PhotoSize = templeupload.PostedFile.ContentLength;
                    tempphoto.PhotoType = templeupload.PostedFile.ContentType;
                    tempphoto.ExtName = tempphoto.PhotoName.Substring(tempphoto.PhotoName.LastIndexOf(".") + 1);
                    tempphoto.TempleID = ans;
                      HttpFileCollection hfc = Request.Files;
                      for (int i = 0; i < hfc.Count; i++)

                      {
                                HttpPostedFile hpf = hfc[i];
                                if (hpf.ContentLength > 0)
                                {
                    int id = new DBTemplePhoto().InsertData(tempphoto);
                    if (id != 0)
                    {
                                    hpf.SaveAs(Server.MapPath("~/templepics/") + ans.ToString() + "." + tempphoto.ExtName);
                                    lblerror.Text = " File is Uploaded ";
                                }
                                     else
                    {
                        ...
                    }
                            }
                      }

However, I noticed that it only uploads one image at a time. While this works for me currently, I would like to implement a feature similar to Gmail where multiple images can be uploaded simultaneously. Can anyone provide guidance on how to modify the existing code for such functionality?

Answer №1

To enhance the functionality of your form on the server side, consider adding "multipart/form-data" to it:

this.Form.Enctype = "multipart/form-data";

Make sure not to recycle the "templeupload" properties; instead, utilize only the "HttpPostedFile hpf" properties from the loop.

If you're looking for a more advanced multiple file uploader, take a look at the JqueryFileUpload plugin: https://github.com/i-e-b/jQueryFileUpload.Net

Answer №2

To enable multiple file uploads, ensure that the "AllowMultiple" attribute is set to true on the file upload control:

<asp:FileUpload ID="uploadFiles" runat="server" CssClass="fileUploader" 
    AllowMultiple="true" />

When handling these files on the server side, iterate through the PostedFiles collection.

foreach(HttpPostedFile file in uploadFiles.PostedFiles)
{
    //perform actions with each file
    file.SaveAs(...);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving the maximum values from JSON data using D3

Currently, I am working with D3 and JSON data by using a function that looks like this: d3.json("http://api.json", function(jsondata) { var data = jsondata.map(function(d) { return d.number; }); After executing this, the value of the data becomes ["2", ...

Changing the Displayed Content with a Simple Click of a Link

Layout Overview In the process of developing a tool to streamline work tasks, I want to ensure that I am following best practices. My goal is for the website to initially display only column A, with subsequent columns generated upon clicking links in the ...

Getting the value of a button using JavaScript

Is there a way to retrieve the value of a button when multiple buttons are generated dynamically? I have a JavaScript function that creates buttons in a list based on my search history, with each button labeled as a city name. However, after clicking on o ...

Positioning the camera directly behind the mesh for optimal framing

I designed a city and a character using Blender, then imported both as JSON objects into my script. My objective is to navigate my character through the city with the character always centered on the screen. However, I'm facing an issue where my chara ...

Incorporate validation features within a jQuery method

I am struggling with some HTML and jQuery code that generates links based on user input. HTML <input type="text" id="text" placeholder="Enter text" autofocus /> <a id="link1" class="btn btn-info" href="#" target="_blank"> Search 1 </a> ...

What is the solution for fixing the "Invalid Element Type" error?

Hey there! I'm currently working on creating a Twitter clone using React, but I've run into an error that's giving me some trouble. The error message reads: "Element type is invalid: expected a string (for built-in components) or a class/fu ...

The SyntaxError message indicates that there was an unexpected non-whitespace character found after the JSON data when parsing it

I received an Error message: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data Here is the code snippet: <script> $(document).ready(function () { $('.edit1').on('change', function () { ...

Can AJAX be used to send a POST request to a Razor page model from a different page? (Illustration)

Trying to enhance my skills in web development, I decided to experiment with using only the POST method of a Razor page/model for an AJAX script to upload a file via another razor page without treating the "FileUpload" page as a standalone page. I'll ...

Parsing XML using jQuery AJAX without the need for the find method

I have been experimenting with implementing ajax in our webservices to optimize the loading speed of certain pages. I have managed to create a working sample, but I am looking for a way to make this process more efficient for use across multiple pages with ...

Utilizing JSON for seamless integration of FullCalendar into Joomla component

I am currently working on integrating FullCalendar with my Joomla component by writing a JSON feed in the controller: public function getAvails() { $app = JFactory::getApplication(); $document = JFactory::getDocument(); $admin_id = $ ...

Display an image when the iframe viewport is reduced in size by utilizing media queries

I am looking to showcase a demo.html page within a 400px square iframe. When the viewport is smaller than 400px, I want demo.html to only display an image. Then, when clicking on that image in demo.html, the same page should switch to fullscreen mode. Sim ...

Issue: $injector:unpr Unknown Provider (app.js is appearing to be properly defined)

Struggling with the unknown provider issue, I've searched through other threads and tried their solutions to no avail. My goal is to inject 'MockSvc' service into a controller without encountering any errors. Any advice would be greatly appr ...

Implement a loader in AngularJS to display when transitioning between pages

Is there a way to implement a loader that appears when the page starts changing and only disappears once the entire page is fully rendered to prevent clipping bugs? I have already set up the loader as shown below: $scope.$on('$routeChangeStart' ...

information not showing up properly

After submitting a form with the code provided, I am experiencing an issue where instead of displaying the message in the div as intended, the screen is refreshing and retaining the completed form in the browser cache. It seems like I have made an error so ...

SignalR blocking axios requests (In a Waiting State)

I am currently developing a project that involves bidding on products in Auctions with real-time updates of the bid price. With potentially thousands or even millions of users worldwide participating in the bidding process. We have implemented SignalR for ...

The transition of a controlled input to an uncontrolled state within a component, along with a partial update to the state

In my project, I have a main component that needs to collect a list of contacts including their name and email: import { useState } from 'react' import AddContactFn from './components/AddContactFn' function App() { const [contacts, ...

Top method for hiding or displaying the "Processing..." notification while executing a time-consuming Java command from an outside source

I have a custom Java class that can be executed from the shell using the syntax "java [command][options]". This class requires input parameters and produces MIDI files as output. My goal is to develop a straightforward web application that reads from a pr ...

Exploring React: Post-mount DOM Reading Techniques

Within my React component, I am facing the challenge of extracting data from the DOM to be utilized in different parts of my application. It is crucial to store this data in the component's state and also transmit it through Flux by triggering an acti ...

When the anchor tag is clicked, I'm displaying the DIV for Customer Testimonials, however, the expansion of its height is not

One way to display customer testimonials is by using flexslider to create a horizontal scroll. The testimonials are hidden and only shown when the "view all testimonials" link is clicked, which can be seen in this JSFiddle example: Working : Demo JQuery ...

Retrieves MySQL SQL findings and converts them into a JSON structure

I'm in the process of integrating Typeahead.js into my website. The Typeahead.js plugin will retrieve data from a remote page that returns JSON, similar to: http://example.org/search?q=%QUERY Here's the PHP code I've written for my site: ...