I am using JQuery to upload files to a folder in my website's root folder via a file upload dialog on a page from the website. This works fine when I run it locally using Casinni but fails when I deploy to a server which hosts the site using IIS 7. Do I need to do anything in IIS to allow such file uploads?
Something along these lines...
<%# Page Language="C#" %>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
try
{
FileUpload1.SaveAs("C:\\Uploads\\" +
FileUpload1.FileName);
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "You have not specified a file.";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Upload Files</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Upload File" /> <br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label></div>
</form>
</body>
</html>
Another source of acquiring this "skill" http://msdn.microsoft.com/en-us/library/aa479405.aspx
Forget it.... misread the whole thing.
Related
hey everyone i am new to using google api get weather update. problem its gives an error..
i set the doctype but problem not solved.. please help me thanks in advance...
.aspx file
<%# Page Language="C#" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
<title>Put Your Title Here</title>
<style type="text/css">
#Panel1
{
width:350px;
}
#Panel1 img
{
float:left;
width:100px;
height:100px;
margin-top:10px;
}
#Panel1 p
{
float:right;
margin-top:-10px;
margin-right:0px;
}
#Panel1 legend
{
background-color:Green;
color:White;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<h1 style="text-align:left">Using The Google Weather API</h1><br />
<div style="text-align:left">
<b>Enter Location (Postal Code or City): </b><asp:TextBox ID="txtLocation" Text="10007" runat="server"></asp:TextBox>
<asp:Button ID="btnGo" runat="server" Text="GO" onclick="btnGo_Click" /><br /><br />
<asp:Panel ID="Panel1" runat="server">
<asp:Image ImageUrl="" runat="server" ID="icon" /> <br />
<p>
Forecast for <b><asp:Label ID="lblLocation" runat="server"></asp:Label></b><br />
Current Condition: <b><asp:Label ID="currCondition" runat="server" Text=""></asp:Label></b><br />
<b><asp:Label ID="temp_f" runat="server" CssClass = "temp" Text=""></asp:Label></b>
<b><asp:Label ID="temp_c" runat="server" Text=""></asp:Label></b><br />
<b><asp:Label ID="humidity" runat="server" Text=""></asp:Label></b><br />
<b><asp:Label ID="wind_condition" runat="server" Text=""></asp:Label></b><br />
Forecast Date: <b><asp:Label ID="lblForecastDate" runat="server" Text=""></asp:Label></b><br />
</p>
</asp:Panel><br />
<div>
<b><asp:Label id="wdcError" runat="server" Visible="false" CssClass="weatherError" ></asp:Label></b>
</div>
</div>
</form>
<br/>
</body>
</html>
.cs file
protected void btnGo_Click(object sender, EventArgs e)
{
// retrieve weather for the zip code entered by the user
getWeatherData();
}
public void getWeatherData()
{
wdcError.Visible = false;
// check for empty zip code field
if (txtLocation.Text.Length == 0)
{
wdcError.Visible = true;
wdcError.Text = "Please enter a location!";
return;
}
// load xml result from Google weather
XDocument xd = XDocument.Load("http://www.google.com/ig/api?weather=" + txtLocation.Text);
// used to determine if a node is missing
int cnt = 0;
cnt = xd.Descendants("forecast_information").Count();
// determine if forecast information was returned for the location entered by user
if (cnt == 0)
{
wdcError.Visible = true;
wdcError.Text = "Forecast Information NOT available for the location";
return;
}
// navigate to the Current Conditions node
var current_conditions = from currentCond in xd.Root.Descendants("current_conditions")
select currentCond;
// navigate to the Forecast Information node
var forcastInfo = from forecastinfo in xd.Root.Descendants("forecast_information")
select forecastinfo;
Panel1.GroupingText = "Today's Weather";
// retrieve city and forecast date information
foreach (var item in forcastInfo)
{
lblLocation.Text = item.Element("city").Attribute("data").Value;
lblForecastDate.Text = item.Element("forecast_date").Attribute("data").Value;
}
// retrieve current weather conditions information
foreach (var item in current_conditions)
{
currCondition.Text = item.Element("condition").Attribute("data").Value;
temp_f.Text = item.Element("temp_f").Attribute("data").Value + "°" + "F";
temp_c.Text = " (" + item.Element("temp_c").Attribute("data").Value + "°" + "C" + ")";
humidity.Text = item.Element("humidity").Attribute("data").Value;
icon.ImageUrl = "http://www.google.com" + item.Element("icon").Attribute("data").Value;
wind_condition.Text = item.Element("wind_condition").Attribute("data").Value;
}
}
If your favourite weather app suddenly stopped working in the last week or so, there’s no point trying to refresh or reinstall it. Google has shut down its weather API without a word and stranded developers who relied on it to power their weather-related applications. What we’re left with is a pile of broken apps that may or may not get fixed.
It's gone my friend try something else
well you can get from here
http://www.yr.no/
http://www.weathercase.net/
MSN weather API list of conditions?
Thanks
It's because your http://www.google.com/ig/api?weather=" + txtLocation.Text is not returning an xml file. The link simply redirects you to google page.
Google killed weather api sometime before.
http://thenextweb.com/google/2012/08/28/did-google-just-quietly-kill-private-weather-api/
Microsoft has a weather API very similar to Google's
Check this example
http://weather.service.msn.com/data.aspx?weadegreetype=F&culture=en-US&weasearchstr=Chicago,IL
Or you can use Wunderground api
My problem is that using the quoted aspx page when i call the closing Dialog from Code Behind the dialog doesn't close.
If i comment the Response Transmit file part of code then the dialog properly close, else the download starts but the dialog remains opened.
Let me know if you have some suggestions, thanks!
ASPX PAGE:
<%# Page Async="true" AsyncTimeout="30" Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register src="CreateUI.ascx" tagname="CreateUI" tagprefix="uc1" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<%--JQuery--%>
<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>
<link href="Styles/jquery-ui-1.10.4.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$('#jobDone').dialog({
autoOpen: false,
draggable: true,
title: "Job completed",
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
});
function showDialog(id) {
$(function () {
$('#' + id).dialog("open");
return false;
});
}
function closeDialog(id) {
$(function () {
$('#' + id).dialog("close");
return false;
});
}
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<!-- ScriptManager to manage UpdatePanel -->
<asp:ScriptManager ID="mainScriptManager" runat="server"></asp:ScriptManager>
<!-- CreateUI Component -->
<uc1:CreateUI ID="CreateUIForm" runat="server" />
<!-- Hidden Field to pass data -->
<asp:Table ID="TableMain" runat="server" CssClass="table">
<asp:TableRow ID="TableRow1" runat="server">
<asp:TableCell ID="TableCell1" runat="server">
<asp:HiddenField ID="UI_Paths" runat="server" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
<!-- div linked to Jquery dialog -->
<div id='jobDone'>
<asp:UpdatePanel ID="UpdatePanelDownload" UpdateMode="Conditional" ChildrenAsTriggers="false" runat="server">
<ContentTemplate>
<asp:Label ID="LabelMessage" runat="server" Text="Operation ended successfully, do you want to download the produced files?</br></br>"></asp:Label>
<asp:Button ID="ButtonDownload" runat="server" Text="Yes" Width="50px" onclick="ButtonDownload_Click" />
<asp:Button ID="ButtonNo" runat="server" Text="No" Width="50px" OnClientClick="closeDialog('jobDone'); return false;" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
CODE BEHIND:
private void DownloadFile(object uiPaths)
{
UIGEN config = (UIGEN)System.Configuration.ConfigurationManager.GetSection("UIGENGroup/UIGEN");
string toPath = config.sharedPath;
if (!toPath.EndsWith(#"\"))
toPath += #"\";
string[] fileNamePaths = uiPaths.ToString().Split(new char[] { '*' });
string zipName = toPath + DateTime.Now.ToString().Replace("/", "_").Replace(":", "_").Replace(" ", "_") + ".zip";
SharpZipLib.CreateZip(zipName, null, fileNamePaths, SharpZipLib.FolderOffset.LastDirOnly);
try
{
FileInfo file = new FileInfo(zipName);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/x-zip-compressed";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
}
catch (System.Exception ex)
{
//To do ...Manage the error
}
//Delete zip from Server Shared Folder
if (File.Exists(zipName))
File.Delete(zipName);
}
protected void ButtonDownload_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
DownloadFile(UI_Paths.Values);
}
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), UniqueID, "closeDialog('jobDone');", true);
}
I found the solution by myself.
The problem is that Response.End(); End the response before the resisted javascrip in ButtonDownload_Click is executed.
I tried the suggested solution (read in other similar threads) to change Response.End() into context.ApplicationInstance.CompleteRequest() but the download doesn't start that way.
So i deleted:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), UniqueID, "closeDialog('jobDone');", true);
from ButtonDownload_Click and i modified the aspx page from this:
<asp:Button ID="ButtonDownload" runat="server" Text="Yes" Width="50px" onclick="ButtonDownload_Click" />
to this:
<asp:Button ID="ButtonDownload" runat="server" Text="Yes" Width="50px" OnClientClick="closeDialog('jobDone');" onclick="ButtonDownload_Click" />
This way the ButtonDownload suddenly close the dialog from javascript then execute the server side ButtonDownload_Click performing the download.
I'm trying to make a simple uploadfile control with ASP.NET,
and it wouldnt work:
Here's my code(.aspx):
<form id="form1" runat="server">
<div>
upload a file now.
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="button1" Text="Upload" runat="server" Width="73px"
onclick="button1_Click" />
<asp:Label ID="Label1" runat="server" Font-Bold="True" ForeColor="#000099">
</asp:Label>
</div>
</form>
and here's my code behind(.cs):
if(fileupload1.HasFile)
{
try
{
if(fileupload1.PostedFile.ContentType == "image/jpeg")
{
if(fileupload1.PostedFile.ContentLength < 51200000)
{
string filename = Path.GetFileName(fileupload1.FileName);
fileupload1.SaveAs(Server.MapPath("~/img/") + filename);
Label1.Text ="File uploaded successfully!";
}
else
Label1.Text ="File maximum size is 500 Kb";
}
else
Label1.Text ="Only JPEG files are accepted!";
}
catch(Exception exc)
{
Label1.Text = "The file could not be uploaded. The following error occured: "
+ exc.Message;
}
}
the file is not presented in the server..
any thoughts?
when I breakpoint, they all goes valid, the application gets to the code, it all working , but won't save it to the folders.
This may or may not work entirely, but you need to include an enctype attribute in your form.
<form id="form1" runat="server" enctype="multipart/form-data">
If you don't do that, browsers won't transfer the file.
See here: https://developer.mozilla.org/en-US/docs/HTML/Element/form#attr-enctype
change
fileupload1.SaveAs(Server.MapPath("~/img/") + filename);
with
fileupload1.PostedFile.SaveAs(Server.MapPath("~/img/") + filename);
I think the problem lies in these two lines
string filename = Path.GetFileName(fileupload1.FileName);
fileupload1.SaveAs(Server.MapPath("~/img/") + filename);
why are you using
string filename = Path.GetFileName(fileupload1.FileName);
It should be simple
fileupload1.SaveAs(Server.MapPath("~/img/") + fileupload1.FileName);
I am trying to upload an image and after uploading i want to show it in the image control. My code is:
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUploadTest" runat="server" />
<asp:Button ID="ShowImage" runat="server" Text="Show"
onclick="ShowImage_Click" />
<asp:Image ID="ImageUploaded" runat="server" Height="150px" Width="150px"
ImageUrl="~/images/blankImage.gif" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ShowImage" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
C# code is:
protected void ShowImage_Click(object sender, EventArgs e)
{
Label1.Text = "";
if (FileUploadTest.HasFile)
{
try
{
if (FileUploadTest.PostedFile.ContentType == "image/jpeg")
{
if (FileUploadTest.PostedFile.ContentLength < 102400)
{
string filename = Path.GetFileName(FileUploadTest.FileName);
string imageSavePath = Server.MapPath("~/images/") + filename;
FileUploadTest.SaveAs(imageSavePath);
ImageUploaded.ImageUrl = imageSavePath;
ImageUploaded.Visible = true;
Label1.Text = "Upload status: File uploaded!";
}
else
Label1.Text = "Upload status: The file has to be less than 100 kb!";
}
else
Label1.Text = "Upload status: Only JPEG files are accepted!";
}
catch (Exception ex)
{
Label1.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
else
{
Label1.Text = "No File !!!";
}
}
But After pressing the show button, the image is uploaded successfully. But the image control got vanished. Can any one help me about it?
Your problem is simply that you have the wrong URL for the image after it is uploaded. Change your code to this:
ImageUploaded.ImageUrl = "~/images/" + filename;
I am trying to upload an image and after uploading i want to show it in the image control. My code is:
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUploadTest" runat="server" />
<asp:Button ID="ShowImage" runat="server" Text="Show"
onclick="ShowImage_Click" />
<asp:Image ID="ImageUploaded" runat="server" Height="150px" Width="150px"
ImageUrl="~/images/blankImage.gif" />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ShowImage" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
C# code is:
protected void ShowImage_Click(object sender, EventArgs e)
{
Label1.Text = "";
if (FileUploadTest.HasFile)
{
try
{
if (FileUploadTest.PostedFile.ContentType == "image/jpeg")
{
if (FileUploadTest.PostedFile.ContentLength < 102400)
{
string filename = Path.GetFileName(FileUploadTest.FileName);
string imageSavePath = Server.MapPath("~/images/") + filename;
FileUploadTest.SaveAs(imageSavePath);
ImageUploaded.ImageUrl = imageSavePath;
ImageUploaded.Visible = true;
Label1.Text = "Upload status: File uploaded!";
}
else
Label1.Text = "Upload status: The file has to be less than 100 kb!";
}
else
Label1.Text = "Upload status: Only JPEG files are accepted!";
}
catch (Exception ex)
{
Label1.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
else
{
Label1.Text = "No File !!!";
}
}
But After pressing the show button, the image is uploaded successfully. But the image control got vanished. Can any one help me about it?
I think you have to set image url to a valid url. Check the result of your Server.MapPath method.
You have to set an URI location to your image.
Morzel