I have absolutely no idea on how to upload multiple files in asp.net using c#,with single upload button.Its not known in advance ,how many files are there.
Can somebody provide me the code in c#??I would be grateful.
Thanks in advance!!
Multiple uploads are not possible using a single upload control (you'll have to upload one file, then repeat the whole process again after the first file has been uploaded).
You can use an IFrame & some JS to rig up one such control which will allow you to upload multiple files at once (But then also, only one file will be posted to the server at a time, and its for the better, for the server).
Or you can use some third party controls created using Java technology (Applets) or in Flash.
This is an example using multiple textboxes and browse buttons to collect the paths of up to 5 files and then uploads them at once.
DotNetJunkies File Upload Tutorial
This one from MSDN uses the File Field Control to accomplish the same thing.
There is a lot of code in both of those articles that should get you well on your way.
You can create one upload input and have a button to add more dynamically using Javascript. When you click the save button, the files will all be in Request.Files.
<script type="text/javascript">
var uploadCount = 2;
function AddUpload()
{
var uploads = document.getElementById("uploads");
var id = "upload" + uploadCount;
uploads.innerHTML += ("<input type='file' id='" + id + "' name='" + id + "' />");
}
</script>
Add Upload
<div id="uploads">
<asp:FileUpload runat="server" ID="upload1" />
</div>
<asp:Button runat="server" ID="btnSave" Text="Save" />
Related
I have 2 pages. One page sends an id number that I will use to upload data from database later on.
I send this id number through the url - location += "fileUploadPage.aspx?"+ ID".
Then I need to upload files on the server side on that page. I need the form to not reload the page, as it's removing my URL extension.
I thought about using sessionStorage - but I feel like it's better in my case, as the user can have multiple tabs open for different items to upload files to.
After uploading the file to a server side - I will also need to convert it into a PDF.
I've been trying to do this for a few days and I couldn't fix it.
I managed to upload a file from a form to a server side folder, but I couldn't deny the reload of the page.
When I did deny the reload of the page the server side function did not execute. Also, I have failed to convert into PDF.
I work with aspx.net c# on serverside.
Sadly I can't share the original code as it's on a closed place, but I made a demo on my local pc:
Any suggestions? I'm new to the area of working with files-never done that before. Any suggestions on refactoring my code or how I move the ID is more than welcomed.
The input number is also a text I will need to add to my file name
after converting it to a PDF.
<form id="myForm" name="myForm" action="FilesProblemPage.aspx" runat="server" style="margin-top: 20px;">
<select id="Number" runat="server">
<option value="3">333333333</option>
<option value="2">222222222</option>
</select>
<label runat="server">
click me to choose a file
<input id="uploadFile" name="uploadFile" style="visibility: hidden" type="file" runat="server" />
</label>
<p id="ChosenFile">no file selected</p>
<asp:Button ID="uploadButton" runat="server" Text="Upload" type="button"
OnClick="uploadButton_Click" BorderStyle="None" CssClass="button" />
</form>
let makat = location.href.split("?")[1];
if (makat == 44459999) {
$("#makat").val("workssss");
$(".checkingTemp")[0].checked = true;
$(".checkingTemp")[1].checked = true;
}
$("#body_uploadFile")[0].addEventListener("change", function (e) {
console.log($("#body_uploadFile")[0].files);
if ($("#body_uploadFile")[0].files[0] != undefined)
$("#ChosenFile").text($("#body_uploadFile")[0].files[0].name);
else
$("#ChosenFile").text("no file chosen");
})
server side :
added :
using System.IO;
protected void uploadButton_Click(object sender, EventArgs e)
{
if (uploadFile.PostedFile != null && uploadFile.PostedFile.ContentLength > 0)
{
string fileName = Path.GetFileName(uploadFile.PostedFile.FileName);
string folder = Server.MapPath("~/TempFiles/");
Directory.CreateDirectory(folder);
uploadFile.PostedFile.SaveAs(Path.Combine(folder, fileName));
try
{
Response.Write("<script>alert('operation success')</script>");
}
catch
{
Response.Write("<script>alert('operation failed')</script>");
}
}
}
well, you could still use session() to pass the ID, but then on first page load (on the next page, you save that ID into ViewState. That way, it will not matter if they have multiple pages open since when they jump to the next page, then on first page load IsPostBack = false, then you transfer to ViewState.
ViewState is per web page, were as session() is global. so, pass the id via session, and FIRST thing on next page is to transfer the value to ViewState.
However, the problem with just using a simple FileUpLoad control, is they are not all that great, and if files are larger, then you don't get any kind of progress during the up-load.
For this reason, I tend to spend some REAL efforts on file uploading. (since it is a pain for developers, and often for users alike). There are a LOT of choices in this area, but I was using the AjaxToolKit in my project, and thus adopted that one.
So, users can drag + drop files, or select many files and then hit a up-load button.
the AjaxToolKit up-loader thus looks like this:
So, the user can select a bunch of files - remove them, do whatever.
Then they can hit the up-load button.
Each file uploads - with a progress bar. And then after up-loading, I display the files uploaded.
eg this:
And the other advantage of the up-loader, is there not really a file size limit - it uploads in small chunks.
So, it really depends on how fancy you want to get, but there are quite a few "up-loader" examples and even some jquery + JavaScript ones that are quite nice.
As suggested, if you not using the AjaxControl toolkit, then you could consider it (it a bit over kill - but the toolkit does have a lot of other nice features).
As noted, you might want to better use at least a asp.net FileUpload control, but it depends on how many files, how large, and what kind of UI your looking for here?
I'm using ajaxFileUpload as described here: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AjaxFileUpload/AjaxFileUpload.aspx
It is working fine except when I have multiple file upload controls on the same page. Specifically, I am trying to upload different files for different questions. When I upload the first on the page, it works fine, but the one lower down on the page will only upload it's file into the answer for the first question.
I'm not sure that makes sense... so it may help you to know that my page is populated with questions dynamically using ascx files. The document ascx file looks like this:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Document.ascx.cs" Inherits="ScholarshipApplication.controls.questions.Document" %>
<ajaxToolkit:AjaxFileUpload OnUploadComplete="UploadComplete" ID="FileUploadControl" MaximumNumberOfFiles="1" runat="server" AllowedFileTypes="png,jpg,jpeg,pdf,tiff,tif,gif" />
<asp:LinkButton ID="downloadButton" runat="server" CausesValidation="false" OnClick="downloadButton_Click" />
And the code behind:
public void UploadComplete(object sender, AjaxFileUploadEventArgs e)
{
entry.data = e.FileName;
entry.setDocumentData(e.GetContents());
this.downloadButton.Text = e.FileName;
}
My initial thoughts are that somehow I need to help the control's generated javascript to know which question it should be triggering when.
I believe this is a bug in control or this was implemented by some non-obvious reason. Actually, this control doesn't support multiple instances on a page. Consider to use AsyncFileUpload control instead or customize a bit sources of the AjaxFileUpload control. If you prefer second option then you need to download sources from here: http://ajaxcontroltoolkit.codeplex.com/SourceControl/BrowseLatest and change AjaxFileUpload.cs file (here is a path: /Server/AjaxControlToolkit/AjaxFileUpload/AjaxFileUpload.cs). What you need to do is to change ContextKey constant to property for combining context key guid with unique id of control:
public class AjaxFileUpload : ScriptControlBase
{
private const string ContextKeySuffix = "{DA8BEDC8-B952-4d5d-8CC2-59FE922E2923}";
private string ContextKey
{
get { return this.UniqueID + "_" + ContextKeySuffix; }
}
Actually, if you'll look on PreRender method of AjaxFileUpload class you'll easy realize reson for such behavior of this control (the first control handle uploads from all sibling controls on a page).
as per my understanding You need a hidden field variable to identify your question id IN UserControl:
<input type="hidden" id="hdnQuestionId" runat="server"/>
while populating/generating question you need to set this variable , and when you upload the doc , fetch this hidden value and use it.
I created a data attribute named "data-upload-type" on ALL AjaxFileUpload controls and set it to the name of the type. Then I set up the client call to grab that value and set a cookie with the same value. The cookie IS received on the server side functions and I branch based on the value I receive.
Here is an example:
function StartUpload(sender, args) {
var t = $(sender._element).attr('data-upload-type');
document.cookie = 'upload-type=' + $(sender._element).attr('data-upload-type') + ';';
}
<asp:AjaxFileUpload ID="afuUploader1" runat="server" OnClientUploadStart="StartUpload" OnUploadComplete="UploadComplete" OnClientUploadComplete="UploadComplete" data-upload-type="UploadType2"></asp:AjaxFileUpload>
Then in your server side upload call simply check Response.Cookies("upload-type").
Works like a charm!
Background:
I am working on an undergrad research project for my CS department. The project is a website for the biology department and a key feature is that the biology students are able to upload their own .xml files and then a *model is built for them on the server side using Matlab.
The front end is in an ASP.NET, javascript and C# environment. My little association with this project is all the knowledge I have of these systems, tools and languages.
Question:
The .xml files I mentioned earlier can take hours to upload and build. My professor wants the user to be able to continue on with the page using models that are already completed while the new model is sent to the background and the user receives an email when it is completed. I've found material for sending the email, but not for continuing with the page.
I heard something about using AJAX to load a page?
Place a file upload control on your page
<asp:FileUpload ID="FileUpload1" runat="server"/>
Build an http handler to handle the file upload:
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
HttpPostedFile fileToUpload = context.Request.Files["Filedata"];
string pathToSave = HttpContext.Current.Server.MapPath("~/Files/")
+ fileToUpload.FileName;
fileToUpload.SaveAs(pathToSave);
//Process file
}
public bool IsReusable {
get {
return false;
}
}
}
Take a look if you can integrate an upload plugin like uploadify into the project(needs jQuery).
<script type = "text/javascript">
$(document).ready(function()
{
$("#<%=FileUpload1.ClientID %>").uploadify(
{
'swf': 'Scripts/uploadify.swf',
'uploader': 'Handler.ashx',
'auto': true,
'buttonText': 'Select File(s)'
});
});
</script>
If you cannot do this, you need to understand how ajax works
Ajax normally uses XMLHttpRequest, which does not allow you encode and send local files to a server.
You could, either use a Flash swf to handle the uploading on the same page, or to use a form that has a target of an invisible 1x1 iframe.
I found the code posted on this blog about file uploads in asp.net
I think having a small i-frame open up, which will actually do the upload, will let your current page continue working.
So on your current page, you ask for file location and file name and all, then open a new page in an i-frame. Let that i-frame know the source file/folder, destination file/folder, and let it work in the background. So now your current page is free to continue its work.
Hope that helps.
Use a headless Java Upload Applet.
Load the file transfer applet in an iFrame, let the user initiate the file transfer and when a user wants to browse the rest of the website, just don't reload the iFrame containing the Java Applet (which will be uploading the file). After the transfer is complete, do a JAvaScript call to close the iframe.
The following example uses a Java Applet by FileCatalyst, but the idea will be practically with any other Java FTP Applet or ActiveX
<script>
var browsePath = "";
function browseAndAdd() {
browsePath = document.FileCatalyst.browseLive(true);
}
function upload() {
document.FileCatalyst.uploadLive();
}
function clearQueue() {
document.FileCatalyst.clearQueue();
}
</script>
<!--Uses onClick for demonstration only-->
<form id="uploadform">
<!--Launch a browse dialog and add the selected file to the queue-->
<input type=button onClick="javascript:browseAndAdd();" value="Browse and Add to Queue" />
<!-- Force upload of whatever is currently found in the transfer queue -->
<input type=button onClick="javascript:upload();" value="Upload">
<!-- Clear transfer queue (can be called only if no transfers are in progress) -->
<input type=button onClick="javascript:clearQueue();" value="Clear Queue">
</form>
Apologies for lack of indentation, I find the stackoverflow markup for inserting code snipets not very user friendly.
You need to set up somekind of asynchronous processing ideally. Personally I like to use Celery and RabbitMQ for my async and messaging.
I came across this question while studying for the Microsoft Web-Application Developer exam,
You are implementing a Web page that allows users to upload files to a Web server. The page includes a
form that has a Submit button.
You want to restrict uploads so that only files smaller than 1 MB can be uploaded.
The answer given was:
Add an ASP.NET FileUpload control and configure it to run on the server.
Add a server-side OnClick handler to the form's Submit button to save the file only if the file size is
allowed
But wouldn't this mean that the file would have already been uploaded to the server? and we are just choosing whether to save it or not? Can it be done on the client Side?
When doing file uploads there are a number of things you can check. On the server side, there is also the maximum request size, which will actually stop an upload. But you are correct, the upload will have been already performed by the time either of these checks are caught.
You can now use the HTML5 File API on supported browsers to be cleverer with file uploads, including retrieving the size of them on the client-side, and even displaying previews. See here for an example: Client Checking file size using HTML5?
using IE :
<html>
<head>
<script>
function getSize()
{
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">
</form>
</body>
</html>
using Chrome or Firefox :
With jQuery and the HTML5 File API specification implemented, you can use this simple snippet to access file properties such as size:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
alert(this.files[0].size);
});
Source : the excellent article on the topic here : http://www.kavoir.com/2009/01/check-for-file-size-with-javascript-before-uploading.html
I am creating a web application for my company that needs to deal with form processing and database manipulation. The application is implemented using .NET Framework 3.5 using C# and Visual Studio 2008 as the IDE and Microsoft SQL Server 2005 as the database.
Here is my problem:
I have a lot of forms
But my boss only want me to create a single page for the database
processing (easier to extend in the future)
I figured out the only way to solve this problem is by having only 1 .aspx file (that contains everything about the database) and having it invoked as a pop up window everytime a forms need to deal with the database.
Here is another problem of mine:
Due to stateless nature of HTTP, I am unable to process and pass
variable between 2 different windows.
I managed to create certain Javascript functions and have the
variable transferred on display, however it can only pass a variable
that is the primary key in the table. To process other columns in
the table is possible but as the consequence I have to write a very
long inline script in my .aspx page and after it is compiled people
can easily view how to access my company database easily. Hence, I
don't favor this (beside to deal with 1 form, I need to create a
long code already, imagine if i have more than 1000 forms!)
So there are two ways you guys can help me:
Suggest another way other than popping up a new window for my
problem, maybe even advise on how it's implemented.
If you think popping up is the solution, you mind to share some
snippets that can help me figure out the variable passing between
two different windows. I can use some advise especially from some
Javascript expert on this :).
Note: Solution must be workable in ASP.NET Framework 3.5 and tested using IE browser version: 8.
P.S: This is a short explanation about my application flow
Let's say I entered data about a product (it has few properties id, name, price, etc) into the database
Later on somehow I want to edit one or few properties of that product, so I have to launch a form which called "editor.aspx"
Instead of entering the product id (which is the primary key) into the form (and edit the data based on the entered product id) and risking to miscalculately edit the correct data, I provide a small button in the form (let's name it btSearch), that will launch a new popup window which contains the gridview of the database of all product (with selection enabled)
Now I just need to browse through the gridview, select a particular row, it will close the popup and I expect to see few data from that row appeared on my original page (in the textboxes/labels)
I hope my explanation above clears the air, thank you.
I recently wrote something like that: A database handler as aspx file. But i invoked it by using ajax / jquery.
When my aspx file is done, i write something to the response stream, some code, a json string, what ever.
Example:
$.post("yourdatabasehandler.aspx", { name: "John", lastname: "Smith" }, function(data) {
alert("Response from page: " + data);
});
In that example, name and lastname are values that are posted to your site. You can access them like that:
string name = Request.Params["name"]
// Do your database , validation and whatever logic here
Response.Write("Cool dude");
The above javascript will alert "Cool dude" after your databasehandler is done. Inside your javascript you can react to the response how ever you want - For example reload a page.
Hope that helps? Regards
"1. Due to stateless nature of HTTP, I am unable to process and pass
variable between 2 different windows."
You very wrong with this comment to start with, trying MSDN and ASP.Net "How to pass values between ASP.Net Web pages". Passing between Windows only requires a little bit more thought and possibly a little Javascript to refresh a parent windows or cause a postback on a shild window etc.
If you're using a popup window, you can always use QueryStrings to pass a value going to your popup.
window.open("popup_page.aspx?id=" + id + "&name=" + name)
to access it in popup_page.aspx
string sID = Request.QueryString("id");
string sName = Request.QueryString("name");
Update: if you're using IE the this might help you.
function ShowPopup(strMessage)
{
var returnValue= window.showModalDialog("popup_page.aspx");
}
popup_page.aspx
<asp:Button ID="btnReturnValue" runat="server" Text="Proceed" OnClientClick="window.returnValue='some message';window.close();" />
Note: Please note this only works in IE, so I suggest consider using the followings instead:
jQuery
AjaxControlToolkit ModalPopup
I personally suggest the use of jQuery. :)
Thank's for all answers, comments. rates, and feedback. Just now I found a very helpful link here. Basically the answer is based on that particular code. I just need to alter some part.
<script language="javascript">
function GetRowValue(val)
{
window.opener.document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").value = val;
// make sure you change the TextBoxId as respective to your creation
window.close();
}
</script>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
<Columns>
<!-- Reserve the code below, as after you configure data source you -->
<!-- will alter this code drastically therefore-->
<!--you have to make sure to paste this code -->
<!-- again inside this Gridview element once you configure your data source -->
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
<!-- This part must be reserved -->
</Columns>
Also remember to specify the connection string and the sql command in the datasource.
The rest just follow that tutorial and copy paste the code entirely.