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);
}
}
?>
Related
this my first question so sorry if the format isn't perfect yet.
I've a small app communicating via an MSMQ, so I decided to make an aspx webpage to monitor the content of that msmq.
I've tested that page in our acceptance server, works perfectly fine.
However, when I test it in our prod server, if the msmq isn't empty, I have an error page saying "SERVER ERROR IN MSMQ MONITORING : Cannot find a formatter capable of reading this message".
Here's the relevant section of the code :
#{
var errorMessage = "";
string queueName = ".\\Private$\\cotfollowupqueue";
System.Messaging.MessageQueue myqueue = new System.Messaging.MessageQueue(#queueName);
System.Messaging.Message[] msgs = new System.Messaging.Message[0];
try {
msgs= myqueue.GetAllMessages();
}
catch (Exception ex)
{
errorMessage = "An error occured : " + ex.Message.ToString();
}
myqueue.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(AwaitingOrder_DTO) });
}
#section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#Page.Title .</h1>< br/>
<h2>Content of the MSMQ</h2>
</hgroup>
<p>This table will show you the content of the MicroSoft Message Queuing used for COT Follow Up.</p>
<p>
<!-- ADD THINGS HERE -->
#errorMessage
<table border="1">
<tr>
<td>COT ID</td>
<td>Row ID</td>
<td>Number of attempts</td>
<td>Next attempt at</td>
<td>Cot Message</td>
<td>Status</td>
<td>Success</td>
</tr>
#foreach (var msg in msgs)
{
myqueue.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(AwaitingOrder_DTO) });
var message = (AwaitingOrder_DTO)msg.Body;
<tr>
<td>#message.COTID</td>
<td>#message.rowId</td>
<td>#message.numberOfRetries</td>
<td>#message.nextAttempt</td>
<td>#message.cotMessage</td>
<td>#message.status</td>
<td>#message.success</td>
</tr>
}
</table>
</p>
</div>
</section>
}
The code is a copy pasta from one server to the other, and the deployment was done exactly in the same way. Would anyone know what I can look at to correct this?
I've searched for solutions but : I have a formatter, so it doesn't seem to be the problem.
The code works on another server, so I guess it might be unrelated to the code itself but to environment.
I've checked with "go to definition" where the page got "awaiting order dto" and "queue writer" definition from, and it sends me to a "from metadata" page which makes me wonder if that might be the trouble, but I highly doubt that, since even if the queue writer isn't in the direct metadata, the page is able to send messages to the msmq, just not to read it's content.
Any idea?
(Sorry for long post)
So, I've found the origin of my problems:
--As stated, the f12/see definition option showed me metadata, but I didn't find any real class/code corresponding.
==> This led me to search information about where you put the code in asp.net web app. Answer is : in "app code folder", which is then compiled to make "app code dll". Guess what? You can't just copy paste that file and hope it'll work, apparently.
So I re-took source code, re-compiled, and replaced the "failing" files. Tadaaa, I can monitor my msmq.
(Also had a typo to correct because the page failed to create correct DTO for the transfer, and had to clean the queue multiple times since it's in prod and I can't simply send wrong informations but hey. That's how you learn).
At least now I'm registered on SO.
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.
A console app in C# that requests four images in a tight loop sometimes returns a previous request. The code is as below and works against any web site, I typically see 3 or 4 errors per run. I developed this code after reports from people browsing a web site I manage where occasionally a jpeg or script would be loaded when the user requested a HTML page.
I don't know if it is a Chrome or ChromeDriver issue. If the previous request was an HTML page then you can end up with getting that instead of the image. Seems to be a race condition.
Has anyone else seen this behaviour and can they repeat it with the code below?
class ContentVerify
{
OpenQA.Selenium.IWebDriver driver;
readonly System.Collections.Generic.List<string> testUrls = new System.Collections.Generic.List<string>()
{
"http://i.imgur.com/zNJvS.jpg",
"http://i.imgur.com/lzVec.jpg",
"http://i.imgur.com/rDuhT.jpg",
"http://i.imgur.com/sZ26q.jpg"
};
public void Check()
{
driver = new OpenQA.Selenium.Chrome.ChromeDriver(); // Both InternetExplorerDriver and FirefoxDriver work OK.
for (int i = 0; i < 10; i++)
{
TestUrls();
}
driver.Quit(); // The driver also crashes on exit, but this seems to be a known bug in Selenium.
}
private void TestUrls()
{
foreach (var item in testUrls)
{
System.Console.WriteLine(item);
//System.Threading.Thread.Sleep(1); // Uncommenting this makes Chrome & ChromeDriver work as expected.
driver.Url = item;
// Requests for images come back as an HTML image tag wrapped in a brief HTML page, like below;
//<html><body style="margin: 0px;"><img style="-webkit-user-select: none" src="http://i.imgur.com/zNJvS.jpg"></body></html>
// So the image should always be in the page, but sometimes (not always) we get the previous image requested.
if (!driver.PageSource.Contains(item))
{
System.Console.ForegroundColor = System.ConsoleColor.Red;
System.Console.WriteLine("Expected: {0}, got: {1}", item, driver.PageSource);
System.Console.ResetColor();
}
}
}
}
It could be that you're not giving the driver enough time to complete the call and have the page load, so it'll "return" whatever previous page it had returned. Have you looked into setting up a timeout/wait on the driver?
EDIT
With regards to the question of why there is this issue in Chrome but not the other browsers, I'd had to venture a guess and say that it probably has to do with how the different browser engines handle displaying an image directly instead of HTML. I make this assumption due to the fact that this discrepancy as described is not seen when running similar code against an HTML page like the Google home page.
Each browser wraps the image in some HTML. For example, IE9 wraps as such:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content="text/html; charset=windows-1252" http-equiv=Content-Type></HEAD>
<BODY><IMG src="[url here]"></BODY></HTML>
Whereas Firefox wraps it like:
<html>
<head>
<meta content="width=device-width; height=device-height;" name="viewport">
<link href="resource://gre/res/TopLevelImageDocument.css" rel="stylesheet">
<title>[filename] (JPEG Image, 500 × 332 pixels)</title>
</head>
<body>
<img alt="[url here]" src="[url here]">
</body>
</html>
And finally, Chrome:
<html>
<body style="margin: 0px;">
<img style="-webkit-user-select: none; " src="[url here]" width="500" height="332">
</body>
<style type="text/css"></style>
</html>
Now, I don't know why the Chrome version causes the webdriver to be unable to detect the pageload. It certainly is the most minimal of the three HTML wrappers, and the w3 validator has a mild panic attack when asked to validate its HTML while the other two validate relatively well.
Also, as mentioned by mootinator, there have been numerous complaints about the Chrome driver in general so it could be just an issue with the Chrome webdriver itself. I just found the above interesting and thought it might be worthwhile to share.
There seem to be a lot of complaints about performance with the Chrome driver.
http://code.google.com/p/selenium/issues/detail?id=1294
Two facts:
1. Chrome itself is not a poorly performing browser.
2. Requests for new URLs are sent asynchronously.
Regardless of what the actual implementation is, it's apparent that the Chrome driver has a performance problem somewhere in the process of making requests and/or updating itself with the results of requests.
The Selenium driver doesn't guarantee that a page will be finished loading before you want to take a peek at it. As such, it can't reasonably be called a bug in the driver if you happen to get a race condition in one of your tests. In order to make reliable selenium tests you need to rely on using, as Roddy indicated, timeout/wait.
I have been using Selenium for sometime now and its always the case where the C# code have finished executing before even the request page was fully loaded, means selenium is very slow in doing its functionality. So in order for selenium to do its stuff we ended using Thread.Sleep and our tests have started working correctly
I agree not the nice way to do it but we have tried various ways and failed to find cleaner solution
Please see link for information Why is Selenium RC so slow? on this same page at the right side their are some related links on other issues related to selenium
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.