I want to validate the file size before upload on IE8+
I tried
Validate File size before upload
But didn't work.
And I can't configure every IE browser to use the "ActiveXObject" (I saw that is one way for the solution).
What I should do?
Using the ASP.NET FileUpload control you cannot use code to validate the size of a file and inform the user.
If you want a better user experience, then I suggest you investigate some open source solutions like the following:
Custom HTTP module
NeatUpload is a free option.
Silverlight/Flash option
SWFUpload is a free option.
Asynchronous chunking option
RadAsyncUpload - Telerik's ASP.NET AsyncUpload is a pay option, check website for pricing.
Try this
<form enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="myFile"><br>
</form>
<script>
$('#myFile').bind('change', function() {
alert(this.files[0].size);
});
</script>
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?
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 want to show up an OpenFileDialog box in my ASP .NET web application. I am writing in c#. I want to create a user account with an image so I need to select image from my computer and save it into a database. How can I implement it.
You can do that using
<input type="file" id="fileLoader" name="files" title="Load File" ...
The usual trick is to make it invisible, and on clicking some visible artifact (styled link, image, button... whatever) simulate a click on fileLoader:
$("#fileLoader").click();
You cannot. OpenFileDialog is something for desktop applications.
you cannot use that Windows Forms class in ASP.NET, you should use the FileUpload class/control.
Or see other alternatives: Uploading Files in ASP.net without using the FileUpload server control
Almost the same as Tigran's above but I found I needed to change the JavaScript slightly to use getElementById("...") to identify the button to click(). If I just did this in HTML/CSS Tigran's code worked fine but when I used it within an .aspx file I required the change.
.aspx
<input type="file" id="fileLoader" name="files" title="Load File" />
<asp:Button ID="LoginButton" runat="server" Text="ASP click Me" onclientclick="openfileDialog()" />
JavaScript
function openfileDialog() {
document.getElementById("fileLoader").click();
}
css
#fileLoader{
display:none;}
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 have a small WPF app (although I guess it doesn't really matter whether it's a wpf form or a webform app?) that I want to have launch a new browser window and POST to a specific url. I've been messing around with:
System.Diagnostics.Process.Start("http://myurl.com");
to launch the window but I don't think I can use the same process to actually post to a url...I've also experimented with HttpWebRequest but I would like the user to be able to use the app after I have posted to this url, not just show them the results...What can I look at to able to do something like this?
There is no direct way to do it. What you could do is generate a HTML page with a form filled with the data you need to post, and a bit of javascript to post the page automatically when it is loaded. Then you just have to open that page in the browser...
The generated HTML could look like that :
<html>
<head>
<script language="Javascript">
function submitForm() {
var theForm = document.getElementById("theForm");
theForm.submit();
}
</script>
</head>
<body onload="submitForm()">
<form id="theForm" action="http://myurl.com" method="POST">
<input type="text" name="username" value="myusername"/>
<input type="password" name="password" value="mypassword"/>
</form>
</body>
</html>
If the page must be displayed in your application, load it in a WebBrowser control
Use the WebBrowser Class instead.
There are multiple solutions, not sure which one would be the best for you...
Proceed with your original approach
Embed web browser control in your applicaiton as suggested in other answers
Do everything programmatically "behind the scene"
For #3 you may want to look here: http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx
If you want to go with #1 - it is more tricky, since you need to control external application and different browsers would behave differently.
I've used "javascript:" protocol and the code below with IE as default browser when dealing with one "user-unfriendly" application. Please note that it's not "production-ready" code. There is no error handling, user may shift focus away from launched browser, or use browser without "javascript:" protocol support etc.
static void Main()
{
Settings s = Settings.Default;
Process.Start(s.URL1);
Thread.Sleep(s.Delay1);
SendKeys.SendWait("%D");
Thread.Sleep(100);
SendKeys.SendWait(EncodeForSendKey(s.URL2));
SendKeys.SendWait("{ENTER}");
}
public static string EncodeForSendKey(string value)
{
StringBuilder sb = new StringBuilder(value);
sb.Replace("{", "{{}");
sb.Replace("}", "{}}");
sb.Replace("{{{}}", "{{}");
sb.Replace("[", "{[}");
sb.Replace("]", "{]}");
sb.Replace("(", "{(}");
sb.Replace(")", "{)}");
sb.Replace("+", "{+}");
sb.Replace("^", "{^}");
sb.Replace("%", "{%}");
sb.Replace("~", "{~}");
return sb.ToString();
}
URL1: http://www.google.com
URL2: javascript:function x(){document.all.q.value='stackoverflow';document.forms[0].submit();} x();
You can create a hidden WebBrowser control and do Navigate() (using the overload that allows you to specify the request method). You will need to specify a "_blank" target frame to cause the navigation to happen in a new browser window.