Uploading Files in ASP.net without using the FileUpload server control - asp.net

How can I get an ASP.net web form (v3.5) to post a file using a plain old <input type="file" />?
I am not interested in using the ASP.net FileUpload server control.

In your aspx :
<form id="form1" runat="server" enctype="multipart/form-data">
<input type="file" id="myFile" name="myFile" />
<asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />
</form>
In code behind :
protected void btnUploadClick(object sender, EventArgs e)
{
HttpPostedFile file = Request.Files["myFile"];
//check file was submitted
if (file != null && file.ContentLength > 0)
{
string fname = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
}
}

Here is a solution without relying on any server-side control, just like OP has described in the question.
Client side HTML code:
<form action="upload.aspx" method="post" enctype="multipart/form-data">
<input type="file" name="UploadedFile" />
</form>
Page_Load method of upload.aspx :
if(Request.Files["UploadedFile"] != null)
{
HttpPostedFile MyFile = Request.Files["UploadedFile"];
//Setting location to upload files
string TargetLocation = Server.MapPath("~/Files/");
try
{
if (MyFile.ContentLength > 0)
{
//Determining file name. You can format it as you wish.
string FileName = MyFile.FileName;
//Determining file size.
int FileSize = MyFile.ContentLength;
//Creating a byte array corresponding to file size.
byte[] FileByteArray = new byte[FileSize];
//Posted file is being pushed into byte array.
MyFile.InputStream.Read(FileByteArray, 0, FileSize);
//Uploading properly formatted file to server.
MyFile.SaveAs(TargetLocation + FileName);
}
}
catch(Exception BlueScreen)
{
//Handle errors
}
}

You'll have to set the enctype attribute of the form to multipart/form-data;
then you can access the uploaded file using the HttpRequest.Files collection.

use the HTML control with a runat server attribute
<input id="FileInput" runat="server" type="file" />
Then in asp.net Codebehind
FileInput.PostedFile.SaveAs("DestinationPath");
There are also some 3'rd party options that will show progress if you intrested

Yes you can achive this by ajax post method. on server side you can use httphandler.
So we are not using any server controls as per your requirement.
with ajax you can show the upload progress also.
you will have to read the file as a inputstream.
using (FileStream fs = File.Create("D:\\_Workarea\\" + fileName))
{
Byte[] buffer = new Byte[32 * 1024];
int read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
while (read > 0)
{
fs.Write(buffer, 0, read);
read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
}
}
Sample Code
function sendFile(file) {
debugger;
$.ajax({
url: 'handler/FileUploader.ashx?FileName=' + file.name, //server script to process data
type: 'POST',
xhr: function () {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return myXhr;
},
success: function (result) {
//On success if you want to perform some tasks.
},
data: file,
cache: false,
contentType: false,
processData: false
});
function progressHandlingFunction(e) {
if (e.lengthComputable) {
var s = parseInt((e.loaded / e.total) * 100);
$("#progress" + currFile).text(s + "%");
$("#progbarWidth" + currFile).width(s + "%");
if (s == 100) {
triggerNextFileUpload();
}
}
}
}

The Request.Files collection contains any files uploaded with your form, regardless of whether they came from a FileUpload control or a manually written <input type="file">.
So you can just write a plain old file input tag in the middle of your WebForm, and then read the file uploaded from the Request.Files collection.

As others has answer, the Request.Files is an HttpFileCollection that contains all the files that were posted, you only need to ask that object for the file like this:
Request.Files["myFile"]
But what happen when there are more than one input mark-up with the same attribute name:
Select file 1 <input type="file" name="myFiles" />
Select file 2 <input type="file" name="myFiles" />
On the server side the previous code Request.Files["myFile"] only return one HttpPostedFile object instead of the two files. I have seen on .net 4.5 an extension method called GetMultiple but for prevoious versions it doesn't exists, for that matter i propose the extension method as:
public static IEnumerable<HttpPostedFile> GetMultiple(this HttpFileCollection pCollection, string pName)
{
for (int i = 0; i < pCollection.Count; i++)
{
if (pCollection.GetKey(i).Equals(pName))
{
yield return pCollection.Get(i);
}
}
}
This extension method will return all the HttpPostedFile objects that have the name "myFiles" in the HttpFileCollection if any exists.

HtmlInputFile control
I've used this all the time.

//create a folder in server (~/Uploads)
//to upload
File.Copy(#"D:\CORREO.txt", Server.MapPath("~/Uploads/CORREO.txt"));
//to download
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName("~/Uploads/CORREO.txt"));
Response.WriteFile("~/Uploads/CORREO.txt");
Response.End();

Related

Throw error message on kendo upload after wrong columns in aspx

I am using kendo upload to upload a file to my server and write the data to db
$('#files').kendoUpload({
async: {
saveUrl: 'test.aspx/ImportExcel'
},
dropZone: '.drop-zone',
multiple: true,
clear: function () {
},
complete: function(){
//This is called when all files are uploaded
},
In back-end aspx i read the excel save it to a datatable and i want to check if the datatable has 3 columns its ok and write the columns in the database else throw a message to the user that the excel is not in the correct format..How can i do this?
if dt.columns.count =3
{ write to database }
else
{ return error to user that the excel is not in correct format };
What you need is a "server side validation" for your uploaded file and a Panel to show a message. In the old asp.net webforms world it should looks like this:
<telerik:RadAsyncUpload runat="server" EnableCustomValidation="true" ID="RadAsyncUpload1" OnFileUploaded="RadAsyncUpload1_FileUploaded" >
</telerik:RadAsyncUpload>
<asp:Panel ID="InvalidFiles" Visible="false" runat="server" CssClass="qsf-error">
<h3>Validation Erros:</h3>
<ul class="qsf-list ruError" runat="server" id="InValidFilesList">
<li>
<p class="ruErrorMessage">Your Excel is not valid...</p>
</li>
</ul>
</asp:Panel>
public void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
{
var liItem = new HtmlGenericControl("li");
liItem.InnerText = "Your uploaded Excel does not look so nice";
InValidFilesList.Controls.AddAt(0, liItem);
e.IsValid = false; // (Add validation (see comment bellow))
}
To validate your Excel file you can use Open XML to check your excel file.

Get File ID in page after upload file by AsyncFileUpload(ajaxToolkit)

I am using AsyncFileUpload (ajaxToolkit) control for uploading image file from registration page. uploaded file content are store into DB. So I need to show my uploaded file in asp:image control by httphander like <asp:image id="imgLogo" runat="server" ImageUrl="Images.aspx/id=12" />. So how to do this.
Assuming you are storing the image as a byte[] in DB;
var data = new byte[1]; //Replace this with your values from DB
var mimeType = "application\pdf"; //Replace this with your values from DB
response.ContentType = mimeType ;
response.BinaryWrite(data);
This code should be placed in page_load in images.aspx after you have retrieved the values from the DB.
Your image page handler page_load method will be
Images.aspx
protected void Page_Load(sender s, eventagrs e){
var imagecontent= new byte[XXXX]; // Read DB content as bytes for the passed Id
response.ContentType = 'jpeg/gif/anything' ;
//this should be a valid MIME type saved in database
response.BinaryWrite(imagecontent);
}
Edit:
From your comments you are trying to update the image tag src value
from codebehind using Asp.Net Ajax.
If you want to do this, first make sure your page has access to view state
information about those image tags. This is not a big deal, you simply
wrap the image tags container panel/div with update panel.
So your ajax request will send the information about those viewstate and
push the partial update for those image container panel also.
I have reviewed many site and I got answer of this question..
http://www.mikeborozdin.com/post/AJAX-File-Upload-in-ASPNET-with-the-AsyncFileUpload-Control.aspx
<ajaxToolkit:AsyncFileUpload ID="afuCompanyLogo" runat="server"
OnClientUploadError="uploadError" OnClientUploadComplete="uploadComplete"
UploaderStyle="Modern" UploadingBackColor="#CCFFFF"
ThrobberID="myThrobber"
onuploadedcomplete="afuCompanyLogo_UploadedComplete" />
<asp:Image ID="imgCompanylogo" CssClass="imgCompanylogo" runat="server" Height="80px" Width="80px" AlternateText="" />
protected void afuCompanyLogo_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if(afuCompanyLogo.HasFile)
{
FileManagementEntity fileManagementEntity = new FileManagementEntity();
FileManagement fileManagement = fileManagementEntity.Create();
fileManagement.FileContentType = afuCompanyLogo.ContentType;
fileManagement.FileContent = afuCompanyLogo.FileBytes;
fileManagement.Size = afuCompanyLogo.FileBytes.Count();
fileManagement.OriginalName = afuCompanyLogo.FileName;
fileManagementEntity.Save(fileManagement);
ViewState["logoID"] = fileManagement.FileManagementID;
imgCompanylogo.ImageUrl = "Image.aspx?id=" + fileManagement.FileManagementID.ToString();
ScriptManager.RegisterClientScriptBlock(afuCompanyLogo, afuCompanyLogo.GetType(), "img", "top.document.getElementById('" + imgCompanylogo.ClientID + "').src='Image.aspx?id=" + fileManagement.FileManagementID + "';", true);
}
}

window.open on load page (ASP.NET) using Method=POST

i need open pop up in asp.net using post Method and window.open to rezise te new windows.
my code:
Open the pop up:
function mdpbch(URL) {
child = window.open(URL, "passwd","dependent=1,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=600,height=475");
child.location.href = URL;
if (child.opener == null) {
child.opener = window;
}
child.opener.name = "opener";
}
URL:
function PagoEnLinea(Banco)
{
switch(x){
case "BCH":
document.frmEnvia.action = SERV + "/llamacom.asp";
url = SERV + "lamacom.asp
alert(url);
mdpbch(url);
document.frmEnvia.submit();
break;
}
}
ASPX:
<body>
<form id="frmEnvia" runat="server" name="formulario" method="post" target="_blank">
<div style="visibility:hidden;">
<asp:TextBox ID="txtXml" runat="server" Visible="true" />
</div>
.....
</body>
on page load (code behind) i create a xml string and put it in the textbox txtXml.
i need use post method becose the server validate te method, and window.open becose need customize the pop up
thanks
I think you should manipulate the object:
parentWindow
Inside the document object; before you submit the form, something like this:
switch(x){
case "BCH":
document.frmEnvia.action = SERV + "/llamacom.asp";
url = SERV + "lamacom.asp
alert(url);
mdpbch(url);
//here you manipulate the parentWindow element
document.parentWindow.scrollbars... (add the attributes you need)
//--
document.frmEnvia.submit();
break;
}
Since you are setting the name of the popup to passwd, you should then be able to set the target attribute of the form to passwd.
So the only change needed is the following:
<form ... target="passwd">

Asp.Net Check file size before upload

I want to check the selected file size BEFORE uploading a file with the asp fileupload component.
I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..)
How can I do that ?
Thanks for your answers..
ASPX
<asp:CustomValidator ID="customValidatorUpload" runat="server" ErrorMessage="" ControlToValidate="fileUpload" ClientValidationFunction="setUploadButtonState();" />
<asp:Button ID="button_fileUpload" runat="server" Text="Upload File" OnClick="button_fileUpload_Click" Enabled="false" />
<asp:Label ID="lbl_uploadMessage" runat="server" Text="" />
jQuery
function setUploadButtonState() {
var maxFileSize = 4194304; // 4MB -> 4 * 1024 * 1024
var fileUpload = $('#fileUpload');
if (fileUpload.val() == '') {
return false;
}
else {
if (fileUpload[0].files[0].size < maxFileSize) {
$('#button_fileUpload').prop('disabled', false);
return true;
}else{
$('#lbl_uploadMessage').text('File too big !')
return false;
}
}
}
I am in the same boat and found a working solution IF your expected upload file is an image. In short I updated the ASP.NET FileUpload control to call a javascript function to display a thumbnail of the selected file, and then before calling the form submit then checking the image to check the file size. Enough talk, let's get to the code.
Javascript, include in page header
function ShowThumbnail() {
var aspFileUpload = document.getElementById("FileUpload1");
var errorLabel = document.getElementById("ErrorLabel");
var img = document.getElementById("imgUploadThumbnail");
var fileName = aspFileUpload.value;
var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();
if (ext == "jpeg" || ext == "jpg" || ext == "png") {
img.src = fileName;
}
else {
img.src = "../Images/blank.gif";
errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file.";
}
img.focus();
}
function CheckImageSize() {
var aspFileUpload = document.getElementById("FileUpload1");
var errorLabel = document.getElementById("ErrorLabel");
var img = document.getElementById("imgUploadThumbnail");
var fileName = aspFileUpload.value;
var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();
if (!(ext == "jpeg" || ext == "jpg" || ext == "png")) {
errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file.";
return false;
}
if (img.fileSize == -1) {
errorLabel.innerHTML = "Couldn't load image file size. Please try to save again.";
return false;
}
else if (img.fileSize <= 3145728) {
errorLabel.innerHTML = "";
return true;
}
else {
var fileSize = (img.fileSize / 1048576);
errorLabel.innerHTML = "File is too large, must select file under 3 Mb. File Size: " + fileSize.toFixed(1) + " Mb";
return false;
}
}
The CheckImageSize is looking for a file less than 3 Mb (3145728), update this to whatever value you need.
ASP HTML Code
<!-- Insert into existing ASP page -->
<div style="float: right; width: 100px; height: 100px;"><img id="imgUploadThumbnail" alt="Uploaded Thumbnail" src="../Images/blank.gif" style="width: 100px; height: 100px" /></div>
<asp:FileUpload ID="FileUpload1" runat="server" onchange="Javascript: ShowThumbnail();"/>
<br />
<asp:Label ID="ErrorLabel" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="SaveButton" runat="server" Text="Save" OnClick="SaveButton_Click" Width="70px" OnClientClick="Javascript: return CheckImageSize()" />
Note the browser does take a second to update the page with the thumbnail and if the user is able to click the Save before the image gets loaded it will get a -1 for the file size and display the error to click save again. If you don't want to display the image you can make the image control invisible and this should work. You will also need to get a copy of blank.gif so the page doesn't load with a broken image link.
Hope you find this quick and easy to drop in and helpful. I'm not sure if there is a similar HTML control that could be used for just general files.
Here I come to save the day! sorry i am 3 years late but, let me reassure everyone that this is quite possible and not to hard to implement! You simply need to output the filesize of the file being uploaded to a control that can be validated. You can do this with javascript, which will not require an ugly postback, where as if you were to use
FileBytes.Length
you will encounter a postback after the end user has selected an image. (I.E. using the onchange="file1_onchange(this);" to accomplish this.). Whichever way you choose to output the filesize is up to you the developer.
Once you have the filzesize then simply output it to a ASP control that can be validated. (I.E. a textbox) then you can use a regular expression for a range to validate for your filesize.
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="^([1-9][0-9]{0,5}|[12][0-9]{6}|3(0[0-9]{5}|1([0-3][0-9]{4}|4([0-4][0-9]{3}|5([0-6][0-9]{2}|7([01][0-9]|2[0-8]))))))$" ErrorMessage="File is too large, must select file under 3 Mb." ControlToValidate="Textbox1" runat="server"></asp:RegularExpressionValidator>
Boom! it's that easy. Just make sure to use the Visibility=Hidden on your ASP control to be validated and not Display=None because Display=none will appear on the page at all (although you can still interact with it through the dom). And Visibility=Hidden is not visible, but space is allocated for it on the page.
check out: http://utilitymill.com/utility/Regex_For_Range for all your regex range needs!
I think it is possible using javascript look here
I think you cannot do that.
Your question is similar to this one : Obtain filesize without using FileSystemObject in JavaScript
The thing is that ASP.NET is a server-side language so you cannot do anything until you have the file on the server.
So what's left is client-side code (javascript, java applets, flash ?)... But you can't in pure javascript and the other solutions are not always "browser portable" or without any drawback
You can do that by using javascript.
Example:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function showFileSize() {
var input, file;
if (typeof window.FileReader !== 'function') {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
bodyAppend("p", "File " + file.name + " is " + file.size + " bytes in size");
}
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='showFileSize();'>
</form>
</body>
</html>
To validate multiple files with jQuery + asp:CustomValidator a size up to 10MB
jQuery:
function upload(sender, args) {
args.IsValid = true;
var maxFileSize = 10 * 1024 * 1024; // 10MB
var CurrentSize = 0;
var fileUpload = $("[id$='fuUpload']");
for (var i = 0; i < fileUpload[0].files.length; i++) {
CurrentSize = CurrentSize + fileUpload[0].files[i].size;
}
args.IsValid = CurrentSize < maxFileSize;
}
ASP:
<asp:FileUpload runat="server" AllowMultiple="true" ID="fuUpload" />
<asp:LinkButton runat="server" Text="Upload" OnClick="btnUpload_Click"
CausesValidation="true" ValidationGroup="vgFileUpload"></asp:LinkButton>
<asp:CustomValidator ControlToValidate="fuUpload" ClientValidationFunction="upload"
runat="server" ErrorMessage="Error!" ValidationGroup="vgFileUpload"/>
I suggest that you use File Upload plugin/addon for jQuery. You need jQuery which only requires javascript and this plugin: http://blueimp.github.io/jQuery-File-Upload/
It's a powerfull tool that has validation of image, size and most of what you need. You should also have some server side validation and client side can be tampered with. Also only checking the file extention isn't good enough as it can be easly tampered with, have a look at this article: http://www.aaronstannard.com/post/2011/06/24/How-to-Securely-Verify-and-Validate-Image-Uploads-in-ASPNET-and-ASPNET-MVC.aspx
$(document).ready(function () {
"use strict";
//This is the CssClass of the FileUpload control
var fileUploadClass = ".attachmentFileUploader",
//this is the CssClass of my save button
saveButtonClass = ".saveButton",
//this is the CssClass of the label which displays a error if any
isTheFileSizeTooBigClass = ".isTheFileSizeTooBig";
/**
* #desc This function checks to see what size of file the user is attempting to upload.
* It will also display a error and disable/enable the "submit/save" button.
*/
function checkFileSizeBeforeServerAttemptToUpload() {
//my max file size, more exact than 10240000
var maxFileSize = 10485760 // 10MB -> 10000 * 1024
//If the file upload does not exist, lets get outta this function
if ($(fileUploadClass).val() === "") {
//break out of this function because no FileUpload control was found
return false;
}
else {
if ($(fileUploadClass)[0].files[0].size <= maxFileSize) {
//no errors, hide the label that holds the error
$(isTheFileSizeTooBigClass).hide();
//remove the disabled attribute and show the save button
$(saveButtonClass).removeAttr("disabled");
$(saveButtonClass).attr("enabled", "enabled");
} else {
//this sets the error message to a label on the page
$(isTheFileSizeTooBigClass).text("Please upload a file less than 10MB.");
//file size error, show the label that holds the error
$(isTheFileSizeTooBigClass).show();
//remove the enabled attribute and disable the save button
$(saveButtonClass).removeAttr("enabled");
$(saveButtonClass).attr("disabled", "disabled");
}
}
}
//When the file upload control changes, lets execute the function that checks the file size.
$(fileUploadClass).change(function () {
//call our function
checkFileSizeBeforeServerAttemptToUpload();
});
});
dont forget you probably need to change the web.config to limit uploads of certain sizes as well since the default is 4MB
https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.85%29.aspx
<httpRuntime targetFramework="4.5" maxRequestLength="11264" />
Why not to use RegularExpressionValidator for file type validation.
Regular expression for File type validation is:
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$"

Accessing input type file at server side in asp.net

I am using the <input type="file" /> tag to upload a file to the server. How do I access the file at the server side and store it at the server? (The file is an image file)
The client side code is :
<form id="form1" action="PhotoStore.aspx" enctype="multipart/form-data">
<div>
<input type="file" id="file" onchange="preview(this)" />
<input type="submit" />
</div>
</form>
Photostore.aspx.cs has
protected void Page_Load(object sender, EventArgs e)
{
int index = 1;
foreach (HttpPostedFile postedFile in Request.Files)
{
int contentLength = postedFile.ContentLength;
string contentType = postedFile.ContentType;
string fileName = postedFile.FileName;
postedFile.SaveAs(#"c:\test\file" + index + ".tmp");
index++;
}
}
I tried uploading a jpg file. Not able to see a saved file. What is going wrong?
You'll need to add id and runat="server" attributes like this:
<input type="file" id="MyFileUpload" runat="server" />
Then, on the server-side you'll have access to the control's PostedFile property, which will give you ContentLength, ContentType, FileName, InputStream properties and a SaveAs method etc:
int contentLength = MyFileUpload.PostedFile.ContentLength;
string contentType = MyFileUpload.PostedFile.ContentType;
string fileName = MyFileUpload.PostedFile.FileName;
MyFileUpload.PostedFile.Save(#"c:\test.tmp");
Alternatively, you could use Request.Files which gives you a collection of all uploaded files:
int index = 1;
foreach (HttpPostedFile postedFile in Request.Files)
{
int contentLength = postedFile.ContentLength;
string contentType = postedFile.ContentType;
string fileName = postedFile.FileName;
postedFile.Save(#"c:\test" + index + ".tmp");
index++;
}
I think the name tag is required on the file input:
<input type="file" name="file" />
Without this, I don’t get anything back.
Further problems that I had which might be specific to my machine:
I get a
Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'.
error at the line
foreach (HttpPostedFile postedFile in Request.Files)
so my final code looks like this:
for (var i = 0; i < Request.Files.Count; i++)
{
var postedFile = Request.Files[i];
// do something with file here
}
Look into the asp:FileUpload control provided by ASP.NET.
If you dont want to use the FileUpload control in the toolbox, Give your input an ID then use form[id] to access the input field and cast it to HtmlInputFile.
example here: http://www.codeproject.com/KB/aspnet/fileupload.aspx
If you give the input-tag an id and add the runat="server" attribute then you can access it easily.
First change your input tag: <input type="file" id="FileUpload" runat="server" />
Then add the following to your Page_Load method:
if (FileUpload.PostedFile != null)
{
FileUpload.PostedFile.SaveAs(#"some path here");
}
This will write your file to a folder of your choice. You can access the PostedFile object if you need to determine the file type or original file name.

Resources