Getting full file path from code behind from file HTML input - asp.net

I used file HTML input instead of FileUpload Web Control. Don't ask why but I just have to!
HTML:
<input type="file" id="image1" class="listUploadAdd" name="ImageAdd1" />
Code behind:
Dim ImageAdd1 As String = Request.Form("ImageAdd1").ToString()
I browsed from "C:/Orange.jpg" to upload and the result in Code Behind is just the image name "Orange.jpg" and not the full "C:/Orange.jpg" which is needed to get the file from local drive to be uploaded.
What is the best way to capture the full image path from code behind to be uploaded onto the server?
Thank you.

Can you add a runat="server" to the input element? :) Then it's pretty easy to store the file on your server
Request.Files("File1").SaveAs("c:\somedir\yourfile.txt")
If you want the original filename and path, try this:
Dim filename As string = Request.Files("File1").FileName
To download the file without using a runat="server" attribute, you can do this:
Dim file = Request.Files("File1")
Dim buf(file.ContentLength) As Byte
file.InputStream.Read(buf, 0, file.ContentLength)
IO.File.WriteAllBytes("C:\somedir\yourfile.txt", buf)
But you have to set the enctype on the form element in the html page:
<form id="yourform" runat="server" enctype="multipart/form-data">

I browsed from "C:/Orange.jpg" to upload and the result in Code Behind is just the image name "Orange.jpg" and not the full "C:/Orange.jpg" which is needed to get the file from local drive to be uploaded.
You won't be able to pull the file off the client's machine. When you're developing your program, the client and the server are the same machine but when you deploy it, the server and client will be different machines. When the code behind executes (on the server), if you try to open C:\Orange.jpg you will be trying to open it off the server's hard disk. This file will probably not exist.
When you upload a file from a web page, it will be posted to the server as part of the POST message. You can get the file out of this from the Form collection. You don't need to convert the uploader to the ASP.NET control, or add the runat="server" attribute. So long as your post the form, which contains the input element it will be submitted to the server.
The file's contents will be stored as a byte array in the form. You can save this byte array as a file to the server's hard disk somewhere.
In summary:
You don't need to know the path to the file on the client's machine, since you can't access it anyway. Use the file data that is posted as part of the form submit instead to save a copy of the file on the server.

Related

Saving a generated html document to specific folder in ASP.NET

So I have written a simple program that creates an html document based on user input into a number of fields. Currently, when the user pressed a button it generates the document and automatically downloads onto the user's machine using the following:
Response.ContentType = "text/plain";
Response.Write(HTML.ToString());
Response.Flush();
Response.End();
But, I would like to have the file written to a folder on the user's machine when a user presses a button. So, let's say I want them to press the button and it automatically writes the file to their desktop. What would this code look like? (c#)
Thank you,
p.s. I have been trying something like this with no luck:
string filename = Server.MapPath("~/C:/Users/Sean/Desktop/new.html");
System.IO.StreamWriter textWriter = default(System.IO.StreamWriter);
textWriter = System.IO.File.AppendText(filename);
textWriter.Write(HTML);
textWriter.Close();
Using ASP.Net, you CANNOT force user to save any file on any specific location. Moreover the file you want user to save is HTML which will be rendered directly on browser i.e. user will not be prompted to save it on their machine.
So to answer your question, you cannot have ANY file automatically saved to user's machine. There has to be some manual intervention by the user(to select the path at which he/she wants to save it.)

Post a file from codebehind

I want to upload a file from codebehind.
I would like to explain my situation a bit.
My existing code is..
I have a fileupload control.
<asp:FileUpload ID="fuSRForm" runat="server" class="file"/>
Then from the codebehind, I check the conditions for that control.
if (fuSRForm.HasFile && (fuSRForm.PostedFile.ContentType.ToString().Trim().ToLower().Contains("pdf") || fuSRForm.PostedFile.ContentType.ToString().Trim().ToLower().Contains("application/vnd.openxmlformats-officedocument.wordprocessingml.document") || fuSRForm.PostedFile.ContentType.ToString().Trim().ToLower().Contains("msword")))
And if the conditions are met,
I used the Sitecore API to upload the file.
This is the part of uploading API.
// creating necessary arguments to be passed to the processor
UploadArgs args = new UploadArgs();
// adding http files collection
args.Files = base.Request.Files;
So, the API is grabbing all posted files by using base.Request.Files
My new situation is that I creat a pdf file when the user click Submit.
Then I save it in a folder named asyncupload
After that I have to upload it to Sitecore using the same API
So, I tried to change the base.Request.Files to my file.
But I am unable to change that.
So, I will have to upload my file using FileUpload control.
FileUpload tempFU = new FileUpload();
tempFU.PostedFile= ????
args.Files = base.Request.Files;
I am stuck right here. I can either post my file from code behind or change the base.Request.Files to my file.
either way, I am stuck. Anyone can solve that?
I'm not sure what your end goal here is. Maybe you could post some more code if I've understood you incorrectly. But here's how to add a file to the Media Library: Brian Pedersen: Adding a file to the Sitecore Media Library programatically
If you are using an <asp:FileUpload /> control, then you can save the file to server disk like this:
string filePath = Path.Combine(Server.MapPath("~/"), "upload/tempfile.tmp");
FileUpload1.SaveAs(filePath);
Then call the AddFile method from the link I provided above:
AddFile(filePath);
You need to use handler in the api you are going to hit and hit it by
using (WebClient client = new WebClient())
{
client.UploadFile(Sitecore Handler, FilePath);
}

asp.net image jpeg not saving correctly

I am trying to save a jpeg image in an uploads folder which has correct permissions setup. When I test the file is being saved (eg: images/uploads/Winter.jpg) but if I try to view the image in my browser or if I attempt to open the image using anything else the image does not display.
I think that the file is not being encoded correctly before saving it to disk but am not very experienced dealing with the saving of files, encoding. Does the below code look ok or do I need to encode the file being uploaded somehow before saving it to disk?
String imgPath = "newsletter\\images\\uploads\\";
String filename = System.IO.Path.GetFileName(upload.PostedFile.FileName);
filepath = imgPath + filename;
filepath = Request.PhysicalApplicationPath + filepath;
upload.PostedFile.SaveAs(filepath);
The file saves to the correct folder but is only 150bytes in size. If I try to browse to the file and view it with an image viewer it does not display correctly.
Encoding shouldn't be a problem - the raw data isn't changing. However, it's possible the browser isn't sending all the data, or that the upload control is deleting the data before you're saving it.
Make sure that you call .SaveAs() before the page begins unloading, and before any additional postbacks. I think we'll need to see more surrounding code to help further.
Another note - by allowing the existing file extension to be used, you're allowing users to upload .aspx files, which could subsequently be executed through a request. Safe filenames are GUIDs and whitelisted file extensions. Using un-sanitized uploaded path information is very dangerous. If you re-use filenames, sanitize them to alphanumerics.

Get file upload data from post data in ASP.NET

I am looping through the posted values on a form with a view to doing something with them (so don't have access to the controls themselves). This is the process I have to take on this project so that is why I'm doing it this way.
On the form I will have a file upload box but I am not sure how I would upload the file that has been selected from it as I can't just do Control.SaveAs(). When I return the posted value using Request.Form.Item[i] I get the file name I chose but not the full path like I would expect.
Can someone point me in the right direction please?
Thanks.
If you want to manipulate the uploaded files directly, and not through a FileUploader control, you should use the Request.Files collection and not the Request.Form
File Upload controls only pass the file name and the contents. I'm not sure why you would need a folder name, especially since the folder name would be for the client - I can't expect that this would have any value to you since you want to save the file on the server.
As I am unsure of your goals, I would recommend using Server.MapPath("~/Folder") to find a suitable folder to save your uploaded files to

checking for the file type(.txt,jpg,etc) and size before uploading

i am trying to uplaod the file . before that i need to check for the file type and size before saving into the specified folder.
i need allow user only upload .jpg, .bmp, .swf,.png,.tiff,
no other fiel like .txt, pdf, .doc and need to check file size is always less than 1 MB. can we do this in javascript or c# coding
2: and before saving the file i need to check if there is any file with a same name in the folder if it is there than alret the user telling a file name exits
and should rename the file
any solution on this would be great
thank you
As for checking the file size and extension prior to uploading, you'll need to use some form of client side control for such. I'd recommend something like http://swfupload.org/.
As for checking to see if the same file name exists on the server prior, you'll need to use one of the pre-upload events from such a component to make an ajax call to the server to verify such.
You can use regular expression to check file type
<asp:RegularExpressionValidator ID="rexpImageE" Display="Dynamic" runat="server"
ControlToValidate="fup1" ErrorMessage="Only .gif, .jpg, .jpeg, .png, .tiff"
ValidationExpression="(.*\.([Gg][Ii][Ff])|.*\.([Jj][Pp][Gg])|.*\.([Bb][Mm][Pp])|.*\.([pP][nN][gG])|.*\.([tT][iI][iI][fF])$)"></asp:RegularExpressionValidator>
and you can check file size on server side like
if (fup1.PostedFile.ContentLength > lengthInBytes)
{
//your message
return;
}
You can only check filename and size after the file is sent to the server in C#.
You can use the FileName property to check the name. To get the file's extension, you can write Path.GetExtension(upload.FileName). Note that the fact that the file's extension is jpg doesn't mean that it's actually a JPEG image.
To check whether the file already exists, write File.Exists(Path.Combine(#"Your folder", upload.FileName))
To get the size in bytes, check upload.PostedFile.ContentLength.
You can find the correct way to do this on MSDN.
Here's a quick snippet which checks the file type:
if (bannerImageUpload.HasFile)
{
if (bannerFileExt == ".jpg")
{
Stream bannerFileStream = bannerImageUpload.PostedFile.InputStream;
bannerFileData = new byte[bannerImageUpload.PostedFile.ContentLength];
bannerFileStream.Read(bannerFileData, 0,
bannerImageUpload.PostedFile.ContentLength);
}
}
It's probably easier to use a RegularExpressionValidator to do this on the client. Note the use of the ContentLength property. Use File.Exists to check directory folder for any existing file with same name as explained by SLaks :-)

Resources