I have jQuery function to validate the file extension of the uploaded file. If the the file does not belong to a desired file extensions then a validation message will be shown and I will clear the value of File Upload via jQuery as
$('#ctl00_ContentPlaceHolder1_FileUpload').val("")
It is working fine in modern browsers but not in IE 8. I also tried
document.getElementById('ctl00_ContentPlaceHolder1_FileUpload').value = ''
but not working also. my full code is
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg', 'bmp']) == -1) {
alert('Image must be .jpg/.jpeg/.gif/.bmp/.png only.');
$('#ctl00_ContentPlaceHolder1_FileUpload').val("");
document.getElementById('ctl00_ContentPlaceHolder1_FileUpload').value = '';
$("#ctl00_ContentPlaceHolder1_FileUpload").focus();
}
IE has some security restriction(read-only) over <input type="file">
So, a workaround would be clone() and replace the current <input>:
if(navigator.userAgent.toUpperCase().indexOf('MSIE') >= 0){
$("input[type='file']").replaceWith($("input[type='file']").clone(true));
} else {
$("input[type='file']").val('');
}
Also, form $('#form')[0].reset(); can be an option in case it is the only field in the form.
Related
I am working to develop a Windows form Project, we should use a Product picture.
Every this working well, we use File.Exists() to check if the file already exists then copy the image to the product Image folder.
if (image.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(image.FileName))
{
_view.FirmLogo.Image = new Bitmap(image.FileName);
_view.LogoURL = Path.Combine(System.IO.Path.GetFullPath(#"..\..\"), #"Resources\ProductImage\", Path.GetFileName(image.FileName));
//
if (File.Exists(_view.LogoURL))
{
File.Delete(_view.LogoURL);
}
//File.Move(#"c:\test\SomeFile.txt", #"c:\test\Test\SomeFile.txt");
File.Copy(image.FileName, _view.LogoURL);
}
The Bug
when we try to update the same file it fired an error:
"because it is being used by another process.
Ex. if we upload pic1, everything is well, we try to change to pic2 great job.
but if we try to back the pic1 fired the error especially if it happens in the same seesion.
I'm having an issue with my php scripts in ASP.NET MVC.
I've deployed to azure services and have double checked that PHP has been enabled.
The php script (upload.php) is:
<?php
if(move_uploaded_file ($_FILES['file'] ['tmp_name'], "Content/{$_FILES['file'] ['name']}")) {
echo "Programme file uploaded successfully. You will be redirected to the content rater in a few seconds..";
header("refresh:3; url=Home/Index");
exit;
}
else {
echo "XML file not uploaded successfully. Unexpected error.";
header("refresh:3; url=Home/Index");
exit;
}?>
I'm attempting to upload the file to the default created folder (in visual studio) 'Content'. I've tried typing the location as (and all have failed):
~/Content/
/Content/
Content/
My form is as follows:
<form action="/Scripts/php/upload.php" method="post" enctype="multipart/form-data">
<label>Select file:</label>
<input type="file" name="file">
<br /><br />
<input type="submit" class="btn btn-success" value="Upload">
</form>
No matter what happens, I'm always taken to the failure message.
I thought my script could be wrong so I've tried the script from W3Schools (the image upload example) and that always fails too.
After some research it seems as though you're unable to upload to your own web directory on Azure - Is this true?
What are my options if this is?
I also have to use php as it's required by a task I'm trying to complete.
After a little fiddling around with your code, I've gotten something that works!
This should work perfectly for you just change the $target_dir. I've tested this on my website. I had the same problems you had with your provided PHP code which leads me to believe that azure is not blocking any type of uploading.
It would be worthwhile doing some checks such as file type, file size and whether the file already exists for security however.
If you are still having problems use var_dump($_FILES); as it simply prints out the variable, this will show whether you actually get the file.
<?php
$target_dir = "Content/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if(isset($_POST["submit"]))
{
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
// Success
print "Received {$_FILES['file']['name']} - its size is {$_FILES['file']['size']}";
} else {
// Failed
print "Upload failed!";
var_dump($_FILES);
}
}
?>
I am trying to get user confirmation from c# code behind file, to confirm if user wants to overwrite the existing file on server of cancel the operation but so far no luck.
this is my code :
if (File.Exists(filePath))
{
string alertMsg = #"confirm('A File already exists with the same name. \n Would you like to overwrite the existing file ?');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Test", alertMsg, true);
}
else
{
fuPSD.SaveAs(filePath);
}
any help would be highly appreciated.
That code will pop up the message if the file exists and save it if it doesn't.
But you will need to take some action on the confirm dialog result on the client side and either trigger a postback or some other server call to perform the operation in the case of the override.
The problem is that your JavaScript registration will ask the user to confirm to overwrite the file after the next page loads. This then poses the issue of telling whether the user confirmed or denied from the server since you're confirm with be client side.
In the past I've used a hidden field to toggle true/false to show a popup from the server side. This gives me the ability to wire up the events to a delegate on the code behind(I.e make my own confirm box with my own buttons). You can still do this without it by I found that it leads to a lot of messy and hard to follow script like callin __doPostback manually.
something like this :
create
<asp:hiddenField id="hf" />* in the aspx file
also put on the JS location a Declaration :
var answer=null;
back to server :
string alertMsg = #"if (confirm('A File already exists with the same name. \n Would you like to overwrite the existing file ?')==true) answer='1'; else answer='0';";
now on the server side :
read :
hf.value
I am working on ASP.NET3.5 platform.
I have used a file upload control and a asp button to upload a file.
Whenever i try to upload a file which contain special characterlike (file#&%.txt) it show
crash and give the messeage
--------------------------------------------------------------------------------
Server Error in 'myapplication' Application.
--------------------------------------------------------------------------------
A potentially dangerous Request.Files value was detected from the client
(filename="...\New Text &#.txt").
Description: Request Validation has detected a potentially dangerous client input
value, and processing of the request has been aborted. This value may indicate an
attempt to compromise the security of your application, such as a cross-site
scripting attack. You can disable request validation by setting
validateRequest=false in the Page directive or in the configuration section.
However, it is strongly recommended that your application explicitly check all
inputs in this case.
Exception Details: System.Web.HttpRequestValidationException: A potentially
dangerous Request.Files value was detected from the client
(filename="...\New Text &#.txt").
Source Error:
An unhandled exception was generated during the execution of the current web
request. Information regarding the origin and location of the exception can be
identified using the exception stack trace below.
--------------------------------------------------------------------------------
how can i prevent this crash using javascript at client side?
A very simple solution is to validate the filename on click of the button (or some other control) that triggers upload like this and stop upload if there is some problem with filename:
<asp:FileUpload ID="fu1" runat="server" />
<asp:Button ID="btn" runat="server" CausesValidation="true" Text="Click"
OnClientClick="return ValidateFileName();" />
<script type="text/javascript">
function ValidateFileName() {
var fu = document.getElementById("<%= fu1.ClientID %>");
var f = fu.value + "";
if ((f.indexOf("#", 0) >= 0) || (f.indexOf("$", 0) >= 0) ||
(f.indexOf("%", 0) >= 0) || (f.indexOf("^", 0) >= 0)) {
alert("Filename: [" + f + "] contains invalid char");
return false;//will stop button click event here
}
return true;
}
</script>
In an answer similar your other question, you cannot "know" the filename of the files that are being uploaded on the client side, because the browser does not let the javascript see that. As I said on that question, you can use something like SWFupload to give you a bit more control on the client-side and detect this if you like.
You can also take a look at this question for some ideas on how to disable the validation on the server-side.
The ASP.NET page validation just allows you to be lazy and not bother checking your inputs for characters which COULD be used for some sort of attack. However, if you're following good programming practices such as Html.Encode-ing things you display and using parameters for SQL queries, this validation is a lot less useful and I find gets in the way!
Disable it for your file upload page by setting validateRequest=false in the page directive. Just make sure you are checking any other values being entered on that page.
I am trying to fix some bugs in a product I inherited, and I have this snippet of javascript that is supposed to hilight a couple of boxes and pop up a confirm box. What currently happens is I see the boxes change color and there is a 5 or so second delay, then it's as if the missing confirm just accepts itself. Does anyone smarter than I see anything amiss in this code?
function lastCheckInv() {
document.getElementById("ctl00$ContentPlaceHolderMain$INDet$txtInvNumber").style.background = "yellow";
document.getElementById("ctl00$ContentPlaceHolderMain$INDet$txtInvNumber").focus();
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_AddCharges").style.background = "yellow";
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_lblFreight").style.background = "yellow";
bRetVal = confirm("Are you sure the information associated with this invoice is correct?");
return bRetVal;
}
The only thing I can think of is if one of the lines before the confirm is throwing an exception and you're never actually getting to the confirm.
If you're using IE, make sure script debugging is enabled. If you're using Firefox, install the Firebug add-on and enable it for your website.
Or, for very primitive debugging, just put alerts after each statement and figure out where it's bombing.
You should use the following method to reference your controls from JavaScript:
document.getElementById(<%= txtInvNumber.ClientID %>).style.background = "yellow"
If that doesn't help, try setting a breakpoint in your JavaScript and stepping through it to see where it's failing.
This test script ran fine for me in IE, Firefox, and Opera. So there doesn't seem to be anything wrong with your basic syntax. The problem is either in the ID's (which doesn't fit with the fact that it acts as if confirmed after 5 seconds) or in some other conflicting JavaScript on the page. It will be difficult to help you without seeing more of the page.
<script language="javascript">
function lastCheckInv() {
document.getElementById("test1").style.background = "yellow";
document.getElementById("test1").focus();
document.getElementById("test2").style.background = "yellow";
document.getElementById("test3").style.background = "yellow";
bRetVal = confirm("Are you sure?");
return bRetVal;
}
</script>
<form method="get" onsubmit="return lastCheckInv();">
<input id="test1" name="test1" value="Hello">
<input id="test2" name="test2" value="Hi">
<input id="test3" name="test3" value="Bye">
<input type="submit" name="Save" value="Save">
</form>
A few thoughts: Could be the .focus() call is hiding your confirm behind the page? Or could it be that one of your control id's is not correct causing, the .style.background references to fail?
You should set the focus after showing the confirm box, otherwise the confirm box will grab focus away, making that line meaningless.
Don't hard-code ASP.Net id's like that. While they typically are consistent, a future version of ASP.net won't guarantee the same scheme, meaning your setting yourself up for pain when it comes time to update this code at some point in the future. Use the server-side .ClientID property for the controls to write those values into the javascript somewhere as variables that you can reference.
Update:
Based on your comment to another response, this code will result in a postback if the function returns true. In that case, there's not point in running the .focus() line at all unless you are going to return false.
I do not like accesing objects directly by
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_lblFreight").style.background = "yellow";
If the object is not returned JavaScript will error out. I prefer the method of
var obj = document.getElementById("ctl00_ContentPlaceHolderMain_INDet_lblFreight");
if(obj)
{
obj.style.background = "yellow";
}
My guess is you are trying to access an object that is not on the DOM, so it never gets to the confirm call.
It might be worth checking that the elements actually exist. Also,try delaying the focus until after the confirm():
function lastCheckInv() {
var myObjs,bRetVal;
myObjs=[
"ctl00_ContentPlaceHolderMain_INDet_AddCharges",
"ctl00_ContentPlaceHolderMain_INDet_lblFreight",
"ctl00$ContentPlaceHolderMain$INDet$txtInvNumber"
];
bRetVal = confirm("Are you sure the information associated with this invoice is correct?");
for (var i=0, j=myObjs.length, myElement; i<j; i++){
myElement=document.getElementById(myObjs[i]);
if (!myElement){
// this element is missing
continue;
}
else {
// apply colour
myElement.style.background = "yellow";
// focus the last object in the array
if (i == (j-1) ){
myObj.focus();
}
}
}
return bRetVal;
}
function lastCheckInv()
{
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_txtInvNumber").style.background = "yellow";
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_txtInvNumber").focus();
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_AddCharges").style.background = "yellow";
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_lblFreight").style.background = "yellow";
return confirm("Are you sure the information associated with this invoice is correct?");
}
The first two lines in your function are wrong, $ are in the UniqueID of an ASP.Net Control.
On Clientside you have to use the ClientID, replace $ with _ .
If you are sure that the Controls exists, the
code above might work.
Is bRetVal actually declared anywhere?
If not, "var bRetVal = confirm...." is a friendly way of telling jscript that it is a variable.