Upload dynamically created XML file using SFTP guidance - asp.net

Currently I am generating an xml file for download using posted fields with the following code:
string attachment = "attachment; filename=" + FileName + ".xml";
Response.ClearContent();
Response.ContentType = "application/xml";
Response.AddHeader("content-disposition", attachment);
Response.Write(Session["FileForDownload"]);
Response.End();
This is working fine.
However I want to sftp upload the generated file to a specified directory on a server.
I have had success in connecting using ssh.net and have been able to create a new directory etc.
My question is how can I generate the file and then sftp it using ssh.net?
I've tried using a file stream with no success. I'm guessing the file needs to be temporarily stored and then retrieved for upload.
This is my current code segment for the specified problem:
SftpClient sftp = new SftpClient("host", "user", "pwd");
sftp.Connect();
sftp.ChangeDirectory("directory/");
Stream fs = File.OpenRead(Server.MapPath(#"filetobeuploaded"));
sftp.UploadFile(fs, Session["FileName"].ToString());
sftp.Disconnect();
I recognize that there won't be a file already on the server to upload.
Any help would be much appreciated as this is the final piece of the puzzle in my application.
Cheers

Fixed: I found a solution by generating a temp XML file in the server, uploading and deleting it. Thanks for your reply anyway

Related

File Download from web site contains the site's HTML, not the intended data

I am working on an ASP.Net/VB.Net web application in which a file is to be generated and sent to the client when a button on the page is clicked. I have the following code to do this:-
Dim text_file_name As String = WriteOutputFile() ' Generate output file
Response.ClearContent()
Response.Clear()
Response.ContentType = "text/plain"
Response.AddHeader("Content-Disposition", "attachment; filename=" + text_file_name + ";")
Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
File.Delete(text_file_name)
This appears to complete and a file is duly downloaded, but on opening it I find it contains the web page HTML, rather than the intended file text. I observe though that the file (extension .csv) is opened up in Excel, so it is getting at least that part of the message.
I have verified that the file is created as intended by leaving out the File.Delete and watching the files accumulate in the server's directory.
In a previous attempt I had
Response.End()
in place of the complete request; this also generated a .csv file, but one containing the details of a thread exception.
Does anyone know what I am doing wrong?
You're sending the intended file name to the browser as a header hint but you aren't actually sending the file itself. To do that, use Response.WriteFile()

File upload in servlet corrupts the file

I am uploading a file using using (Valums uploader) and I using servlet at server side. File type is application/pdf. Code is :
String filename= request.getHeader("X-File-Name");
InputStream is = request.getInputStream();
File tmp = File.createTempFile(filename, "");
tmp.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmp);
IOUtils.copy(is, fos);
byte[] bytes = new byte[(int) tmp.length()];
is.read(bytes);
Now these bytes are getting stored into database as longblob. But it seems that inputStream in above code is adding some more data in the file thats why file data is getting corrupted. I download the same data as pdf file, found that both- original uploaded file and now downloaded file have the same size, but when the downloaded file is opened in Acrobat, it reports "File is corrupted". For upload request I have used only file input. So there are no chances of other input params in inputStream. Also the bytes array in above code are as it is passed for download. Why is data getting corrupted?
Your problem might be the data length you are reading. I had similar problem and posted on this issue link
Java: Binary File Upload using Restlet + Apache Commons FileUpload
Hope this helps

Viewing file using asp.net

In our application, we allow user to upload documents which can be PDF, Doc, XLS, TXT. Uploaded documents will be saved on web server. We need to display link for each document user uploaded and when user click on that link, it should open relevant document. it is expected to have required software to open relevant documents.
To upload document, we use saveAs method of FileUpload control and it works absolutely fine.
Now, how to view it?
I believe, i need to copy/download file to local user machine and need to open it using Process.Start.
For that i need to find user local temp directory. if i put path.GetTempPath(), it gives me web server directory and copy file there.
File.Copy(
sPath + dataReader["url"].ToString(),
Path.GetTempPath() + dataReader["url"].ToString(),
true);
Please advise.
You can't write to the user's drive from the webserver.
What you can do is just provide a link that will download the file to the client.
Set the Content-Disposition header to "attachment" to have a "save as" dialog come up, or to "inline" to let it display in the browser using the registered program from the client.
You can create a LinkButton with a server side handler that contains code like this:
byte[] data = ...; // get the data from database or whatever
Response.Clear(); // no contents of the aspx file needed
Response.CacheControl = "private";
Response.ContentType = "application/pdf"; // or whatever the mimetype of your file is
Response.AppendHeader("Content-Disposition", "attachment;filename=statistic.pdf");
Response.AppendHeader("Content-Length", data.Length.ToString(CultureInfo.InvariantCulture));
Response.BinaryWrite(data);
Response.End(); // no further processing of the page needed
Can you not just put a link on the page pointing to the directory that the files are in?
e.g.
<a href=downloadedfiles/filename.pdf> click here </a>
Once you've provided the link, your job is done. Mostly. The client's browser will handle loading the file when the link is clicked, if it can handle the file type based on the file extension.
I prefer to use a http handler for referencing file links on a web page. This will be important on the day when you need to implement security for uploaded file access; otherwise, any user could access any file.
You don't have to download the file to user machine.
// For pdf documents
Response.Clear();
string filePath = "File path on the web server";
Response.ContentType = "application/pdf"; // for pdf
Response.WriteFile(filePath);
// For word documents
Response.Clear();
string filePath = "File path on the web server";
Response.ContentType = "application/msword";
Response.WriteFile(filePath);
// similarly other file types

When downloading a file using FileStream, why does page error message refers to aspx page name, not file name?

After building a filepath (path, below) in a string (I am aware of Path in System.IO, but am using someone else's code and do not have the opportunity to refactor it to use Path). I am using a FileStream to deliver the file to the user (see below):
FileStream myStream = new FileStream(path, FileMode.Open, FileAccess.Read);
long fileSize = myStream.Length;
byte[] Buffer = new byte[(int)fileSize + 1];
myStream.Read(Buffer, 0, (int)myStream.Length);
myStream.Close();
Response.ContentType = "application/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + filename);
Response.BinaryWrite(Buffer);
Response.Flush();
Response.End();
I have seen from: ASP.NET How To Stream File To User reasons to avoid use of Response.End() and Response.Close().
I have also seen several articles about different ways to transmit files and have diagnosed and found a solution to the problem (https and http headers) with a colleague.
However, the error message that was being displayed was not about access to the file at path, but the aspx file.
Edit: Error message is:
Internet Explorer cannot download MyPage.aspx from server.domain.tld
Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later.
(page name and address anonymised)
Why is this? Is it due to the contents of the file coming from the HTTP response .Flush() method rather than a file being accessed at its address?
Even though you are sending a file, it is the "page" that contains the header information that describes the file you are sending. The browser still has to download that page, then sees the "attachment; filename=" and gives you the file instead.
So if there is an error, it will be page that is shown as the problem. It's a bit like getting a corrupted email with an attachment, you seen the problem in the email not the attachment itself.
Don't call Response.End();

How to implement a file download in asp.net

What is the best way to implement, from a web page a download action using asp.net 2.0?
Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc.
Does this help:
http://www.west-wind.com/weblog/posts/76293.aspx
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition","attachment; filename=logfile.txt");
Response.TransmitFile( Server.MapPath("~/logfile.txt") );
Response.End();
Response.TransmitFile is the accepted way of sending large files, instead of Response.WriteFile.
http://forums.asp.net/p/1481083/3457332.aspx
string filename = #"Specify the file path in the server over here....";
FileInfo fileInfo = new FileInfo(filename);
if (fileInfo.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Flush();
Response.TransmitFile(fileInfo.FullName);
Response.End();
}
Update:
The initial code
Response.AddHeader("Content-Disposition", "inline;attachment; filename=" + fileInfo.Name);
has "inline;attachment" i.e. two values for Content Disposition.
Don't know when exactly it started, but in Firefox only the proper file name was not appearing. The file download box appears with the name of the webpage and its extension (pagename.aspx). After download, if you rename it back to the actual name; file opens successfully.
As per this page, it operates on First Come First Served basis. Changing the value to attachment only solved the issue.
PS: I am not sure if this is the best practice but the issue is resolved.

Resources