upload to ftp asp.net - asp.net

Is it possible to upload a file directly into an ftp account folder with ASP.NET ?
E.g. I click on browse, select a file to upload and when I click "upload" button, It should save it directly to the folder on another web server located at somewhere else other then the server that is being used to upload.

As I understand your question, you want to upload the file to another remote server (so it's not another server sitting on the same network as your web server)? In that case you can do a couple of different things. The easiest way is perhaps to start by making a regular file upload you your server, and then have your server send the file via FTP to the other remote server:
string fileName = Path.Combine("<path on your server", FileUpload1.FileName);
FileUpload1.SaveAs(fileName);
using(System.Net.WebClient webClient = new System.Net.WebClient())
{
webClient.UploadFile(
New Uri("ftp://remoteserver/remotepath/" + FileUpload1.FileName),
localFile);
}
...or it might work doing it in one step:
using(System.Net.WebClient webClient = new System.Net.WebClient())
{
webClient.UploadData(
New Uri("ftp://remoteserver/remotepath/" + FileUpload1.FileName),
FileUpload1.FileBytes);
}
(I din't try this code out, so there could be some errors in it...)
Update: I noticed that I was wrong in assuming that the UploadXXX methods of WebClient were static...

You can use the WebClient class to store the uploaded file to FTP (without saving it as a file on the server). Something like this:
string name = Path.GetFileName(UploadControl.FileName);
byte[] data = UploadControl.FileBytes;
using (WebClient client = new WebClient()) {
client.UploadData("ftp://my.ftp.server.com/myfolder/" + name, data);
}

/// <summary>
/// Example call : if (FtpUpload(FileUploadControl1, "ftp.my.com/somePathDir", #"user", "pass!", "domain"))
/// </summary>
/// <param name="file"></param>
/// <param name="ftpServer"></param>
/// <param name="username"></param>
/// <param name="ftpPass"></param>
/// <returns></returns>
private bool FtpUpload(FileUpload file, string ftpServer, string username, string ftpPass, string domainName = "")
{
// ftp://domain\user:password#ftpserver/url-path
// If you are a member of a domain, then "ftp://domain-name\username:password#url-path" may fail because the backslash (\) is sent in as a literal character and Internet Explorer incorrectly looks for a file instead of parsing a Web address. Changing the backslash (\) in the domain-name\username to domainname%5Cusername works correctly.
try
{
string ftpAddres;
if (domainName != string.Empty)
ftpAddres = "ftp://" + domainName + #"%5C" + username + ":" + ftpPass + "#" + ftpServer + "/" + file.FileName;
else
ftpAddres = "ftp://" + username + ":" + ftpPass + "#" + ftpServer + "/" + file.FileName;
using (var webClient = new System.Net.WebClient())
{
webClient.UploadData(new Uri(ftpAddres), file.FileBytes);
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return true;
}

You cannot upload it to an FTP directly from your HTML form. However, you can upload it to your ASP.NET application and then upload it to the FTP from there using FtpWebRequest.

EDIT
First off the # sign is there to flag the string as a literal. it saves you having to escape characters like backslashes. e.g.
string path = "Z:\\Path\\To\\File.txt";
string path = #"Z:\Path\To\File.txt";
Secondly, if you only have FTP Access to the other server, then you can take, the FileUpload.FileBytes Property of the FileUpload control. That will give you a byte[] of the file contents.
From this you use the System.Net.FtpWebRequest & System.Net.FtpWebResponse to upload your file to the FTP Account.
Theres some sample code here in VB.NET but it should be easy enough for you to figure out
http://www.programmingforums.org/thread15954.html
ORIG
The file upload control will provide you with the File on your webserver.
It would be up to you, to copy/save that file then from the webserver to whatever server
you're FTP is hosted on.
Do you have a UNC Path/Mapped Drive shared out on your other server that you can save to.
The FileUpload Control has a .SaveAs() method so it's just a simple matter of
if (FileUpload1.HasFile)
try
{
FileUpload1.SaveAs(#"Z:\Path\On\Other\Server\" + FileUpload1.FileName);
}

Related

how to send an image via email without saving it to a folder before

I am uploading images to an asp.net website using fileupload and i need to send the uploaded images via email to do this i am saving the image to a folder on the erver and then i am sending the image but can i send it without saving it to a folder before or if i need to save it to a folder can i delete it as soon as it's sent?
thanks.
my code:
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("UploadImages/" + filename));
string attachmentPath = Server.MapPath("UploadImages/" + filename);
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentType.Name = Path.GetFileName(attachmentPath);
mail.Attachments.Add(inline);
using System.Net.Mail;
[WebMethod]
public void SendFile(HttpPostedFileBase file)
{
//...setup mail message etc
Attachment attachment = new Attachment(file.InputStream, file.FileName);
message.Attachments.Add(attachment);
}

is there a way to query a stream in c#, ex. select * from a streamobject

I have a file upload control in my asp.net (c#) website, which is used to upload csv files with data to be inserted into the database, my problem is that, I was not able to get the actual path of the uploaded file
It always gave me: C:\inetput\projectfolder\csvname.csv
where it should have been similar to: C:\Documents and settings\Pcname\Desktop\csvname.csv
but by going through the various post of file upload, i came to know that file need to be saved on the server first,
using Fileupload1.Saveas(savepath);
which is mandatory to save the file in a previously specified location, where this not actually required. (since it will increase the overhead of again deleting the file).
then what I do is as below:
bool result = true;
strm = FileUpload1.PostedFile.InputStream;
reader2 = new System.IO.StreamReader(strm);
// **** new ****
FileInfo fileinfo = new FileInfo(FileUpload1.PostedFile.FileName);
string savePath = "c:\\"; // example "c:\\temp\\uploads\\"; could be any path
string fileName = fileinfo.Name;
string strFilePath = savePath.ToString();
savePath += fileName;
FileUpload1.SaveAs(savePath);
string strSql = "SELECT * FROM [" + fileinfo.Name + "]";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";" + "Extended Properties='text;HDR=NO;'";
// load the data from CSV to DataTable
OleDbDataAdapter oleda = new OleDbDataAdapter(strSql, strCSVConnString);
DataTable dtbCSV = new DataTable();
oleda.Fill(dtbCSV);
if (dtbCSV.Columns.Count != 2)
{
result = false;
}
because I want to count the number of columns in the file, I'm using the oledb reader.
which needs a file to be queried.
Is it possible to Query a stream? I dont want to save the file, instead just read it without saving.
Unfortunately you cannot use OLEDB against a stream.
In situations where it is mandatory to use OLEDB I've managed to write an IDisposable wrapper that would provide a temporary file from a stream and manage deletion.
You could however go for an alternate approach to reading the contents, without saving it, such as parsing the file yourself directly from a stream. I would recommend this instead of the wrapper since you avoid file access restriction problems as well as the overhead of file access.
Here's an SO with several different approaches.

Images not displaying in adrotator where its picture path like "C:\Uploader\Image.jpg"

Images not displaying in adrotator where its picture path like "C:\Uploader\Image.jpg" or some shared folder in server.If i give the path inside my project,its working but outside the project ( like "C:\Uploader\Image.jpg") it not showing anything.
<telerik:RadRotator ID="radSlider" runat="server" FrameDuration="400" ScrollDuration="500"
ScrollDirection="Left" Height="250px" Width="550px">
<ItemTemplate>
<img src='<%# Eval("FullName") %>' alt="Friday" width="550px" />
</ItemTemplate>
</telerik:RadRotator>
Here i am attaching the path dynamically using databind.What is the problem.Plz help me?Telerik or asp control
The client browser will never know where those images are unless you map a virtual directory to the images. Even you can not use Server.MapPath() etc to map the drive.
You should use an HttpHandler to access the file outside of your
application virtual directory.
Check following SO thread that much relevant to your problem:
Show Images from outside of ASP.NET Application
Another approach that i have gotten after goggle about this as follow:
You can try to access the file outside application's virtual directory. you need to pay attention to the folder/file enough permission.
you can to access the images in your website, you can check the following link:
Displaying images that are stored outside the Website Root Folder
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["FileName"] != null)
{
try
{
// Read the file and convert it to Byte Array
string filePath = "C:\\images\\";
string filename = Request.QueryString["FileName"];
string contenttype = "image/" +
Path.GetExtension(Request.QueryString["FileName"].Replace(".","");
FileStream fs = new FileStream(filePath + filename,
FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
//Write the file to response Stream
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contenttype;
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
catch
{
}
}
}
Hope this help.
You should use IHttpHandler to serve your files in a different location (e.g. outside of application root or in privileged folders). AFAIK, Telerik Rad Controls has a RadBinaryImage or something for such usages.

how to get the full path of file upload control in asp.net?

i am using asp.net 2.0 in my project using file upload control , so browse the drive and select the file like path(D:\user doc new 2011\Montana\MT_SUTA_2010-2011.html)
but in my code seeing error is could not find the file path is
(D:\Paymycheck\OnlineTaxUserDocumentation-1\TaxesDocument\MT_SUTA_2010-2011.html) actually it is application path and take the filename only my code is
if (FileUpload.HasFile)
{
string filepath = Server.MapPath(FileUpload.FileName);
string strHTML = File.ReadAllText(filepath);
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] file1 = encoding.GetBytes(strHTML);
int len = file1.Length;
byte[] file = new byte[len];
docs.TaxAuthorityName = ddlTaxAuthority.SelectedItem.Text;
docs.TaxTypeID = ddlTaxType.SelectedValue;
docs.TaxTypeDesc = ddlTaxType.SelectedItem.Text;
docs.EffectiveDate = Convert.ToDateTime(txtEffectiveDate.Text);
docs.FileName = f1;
if (ddlTaxAuthority.SelectedValue == "FD")
{
docs.Add(strHTML, file1);
}
}
error occoured in this line
string strHTML = File.ReadAllText(filepath);
i can try like this also
string FolderToSearch = System.IO.Directory.GetParent(FileUpload.PostedFile.FileName).ToString();
string f = Path.GetDirectoryName(FileUpload.PostedFile.FileName);
string f1 = FileUpload.FileName;
string filepath = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);
string strFilePath = FileUpload.PostedFile.FileName;
string file1234 = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);
string filepath = FileUpload.PostedFile.FileName;
so how to get the total path drive to file
pls help me any one
thank u
hemanth
Because your are using Server.MapPath, which according to MSDN "maps the specified relative or virtual path to the corresponding physical directory on the server." You have to first call FileUpload.SaveAs method to save file on server then try to read it's content.
If you want the total client side drive path like D:\user doc new 2011\Montana\MT_SUTA_2010-2011.html for the file MT_SUTA_2010-2011.html to be uploaded via fileupload control, then try using System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName).
This will surely return the client side path of the file.
Try this it will work
string filepath = System.IO.Path.GetFullPath(fuldExcel.PostedFile.FileName);
fuldExcel.SaveAs(filepath); //fuldExcel---is my fileupload control ID

viewing the images problem

Using ASP.Net and VB.Net
Code
Image1.ImageUrl = "c:\Blue hills.jpg"
The above code is not viewing the image when i clicked the button.
How to solve this problem.
Need Code Help
You shouldn't be referencing the local file path - you should set the ImageUrl to be the URL on the webserver - for example, if you had the file in the root of your website, you'd reference it as:
Image1.ImageUrl = "/Blue%20hills.jpg"
The value you are supplying to the ImageUrl property is a file path and not a Url.
Ideally you should have a folder in your ASP.NET application that holds your image files which you can then reference with either a relative or absolute Url path i.e:
Image1.ImageUrl = "/Content/Images/Blue hills.jpg"
If you want to show pictures from the server disk that are outside of the website root, you have to build "proxy" page. For example call it ShowImage.aspx and it will get the picture name on the URL.
Then you'll have such code
Image1.ImageUrl = "ShowImage.aspx?image=Blue hills.jpg"
And the code for ShowImage.aspx code behind:
string imageName = Request.QueryString["image"] + "";
if (imageName.Length == 0 || imageName.Contains("/") || imageName.Contains("\\") || !imageName.ToLower().EndsWith(".jpg"))
{
throw new Exception("Invalid image requested");
}
else
{
string strFullPath = "C:\\" + imageName;
Response.ContentType = "image/jpeg";
Response.Clear();
Response.WriteFile(strFullPath);
}
Response.End();
This is C# but should be simple enough to translate into VB.NET as well.
Edit: added basic validation that verify that user does not try to fetch files from different directory and allows only .jpg files.
Image1.ImageUrl = System.Web.HttpContext.Current.Server.MapPath("~") + "/"+ "Images" + "/" + "Blue hills.jpg";
but as said before you can't reference a local file like this , except u use HttpHandler.
http://www.15seconds.com/issue/020417.htm

Resources