I have a simple ASP.NET page that users can browse to, select a file from their machine and upload it to my server. My remote users wish to automate uploading of files (using CURL) at their end.
As there is no user to click a button I need to do something to handle this, but what?
What changes do I need to make to have my web page handle the file upload without clicking a button?
Code Page…
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
namespace FileUpload
{
public partial class _Default : System.Web.UI.Page
{
string UploadTo_Path = ConfigurationManager.AppSettings.Get("UploadTo_Path");
protected System.Web.UI.HtmlControls.HtmlInputFile File1;
protected void Page_Load(object sender, EventArgs e){ }
protected void Button1_Click(object sender, EventArgs e)
{
UploadFile();
}
private void UploadFile()
{
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
UploadTo_Path += "\\" + fn;
File1.PostedFile.SaveAs(UploadTo_Path);
Response.Write("The file has been uploaded.");
}
else
{
Response.Write("Please select a file to upload.");
}
}
}
}
Front End…
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FileUpload._Default" Trace="true" %>
<!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" >
<head runat="server">
<title>File Upload</title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<input type="file" id="File1" name="File1" runat="server" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
</body>
</html>
I’d do this differently.
I’d check if the page was accessed using POST and then run UploadFile(), I wouldn’t use button with a click handler.
On the client side the form would just do a normal form submit (a POST) to the page.
This then lets CURL also access the page directly, without the need to do anything clever with JavaScript (which could be disabled and CURL doesn’t do).