Post a file from codebehind - asp.net

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);
}

Related

Access request after upload (ASP classic)

So, as I figured out, when I have a form with enctype="multipart/form-data" and I upload a file, I can no longer access the object request. The following error is shown:
Cannot use the generic Request collection after calling BinaryRead.
After checking some resources, I stumpled upon a statement, which says: "This is by design". Well, okay, not here to judge about design-decisions.
To give you a quick overview, let me walk you through the code:
if request("todo") = "add" then
Set Form = New ASPForm
category = request("category")
title = request("title")
if len(Form("upload_file").FileName) > 0 then
filename = Form("upload_file").FileName
DestinationPath = Server.mapPath("personal/allrounder/dokumente/")
Form.Files.Save DestinationPath
end if
end if
Nothing too special here so far. Later however, when I try to access my request object, the error mentioned above occures:
<% if request("todo") = "new" then %>
...
My question now, how to get rid of it or fix this. I don't want to open the upload in a popup if there is another way around. This is the only solution I could think off.
Perfectly would be an object, which checks Form and request. Alternatively maybe a check at the top of the file, which object I have to use?
Thanks for any suggestions.
There used to be a very popular ASP class/component that solved ASP file uploads. The site for that component has been taken down, but the code is mirrored here:
https://github.com/romuloalves/free-asp-upload
You can include this ASP page on your own page, and on your page instantiate the class to get access to the files in your form, but also to the form variables. Here is a piece of example code (Upload.Form accesses the form fields):
Dim uploadsDir : uploadsDir = server.mapPath(".") ' whatever you want
Dim Upload, ks, fileKey, mailto
Set Upload = New FreeASPUpload
call Upload.Save(uploadsDir)
ks = Upload.UploadedFiles.keys
for each fileKey in ks
Response.write(fileKey & " : " & Upload.UploadedFiles(fileKey).FileName & "<br/>")
next
mailto = Upload.form("mailTo")
Set Upload = Nothing
If you want to stick to your own implementation, you can probably figure out how to get to the form variables in a multipart/form-data encoded data stream by having a look at the code they use to do so.

Upload File with FileUpload and Stock in database using Framwork entity

I want to upload file with file upload and stock in DataBase SQLserver using framework entity , I use this code :
string strRealPath = Request.PhysicalApplicationPath;
if(FileUpload1.HasFile)
{
string fileName = FileUpload1.FileName;
FileUpload1.SaveAs(strRealPath + fileName);
//Now insert the file into the database.
}
f.photo = Convert.ToString(FileUpload1.FileBytes);
But I find anything added .I use the debugger he tell me that posted file is null
Thanks
Firstly, your form should be encrypted as multipart/form-data. Add parameter to your form tag like below:
enctype = "multipart/form-data"
Secondly you have to send file as controller parameter HttpPostedFile.
This tutorial will be useful for you. Let us know, does it work properly.
===EDIT===
When it comes to database. You have to have column of binary type (varbinary[max]), and you
should try save it there (remember about try/catch). To read content of the file, use stream reader.

Getting full file path from code behind from file HTML input

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.

How can I rename a file in ASP.NET?

In my project I want to rename the file before it is updating. For example a file in my system like Mycontact.xls. I want to rename it as sasi.xls (it is an excel file). How can I write the code in ASP.NET?
Actually I am using a fileupload control to get the file in and rename the file and upload the renamed file in a folder which is in Solution Explorer.
You can do it with the File.Move method eg:
string oldFileName = "MyOldFile.txt";
string newFileName = "MyNewFile.txt";
File.Move(oldFileName, newFileName);
C# does not provide a file rename function, unfortunately. Anyhow, the idea is to do this:
File.Copy(oldFileName, NewFileName);
File.Delete(oldFileName);
You can also use - File.Move.
Be aware that when that code executes, the owner of the file will turn into the identity you have set on your Application Pool on which the website is running.
That account might not have enough permissions to 'create new' or 'delete' files.
I would advise you to place all read/writable files in a seperate location so you can control the security settings seperately on that part. This will also split off the 'only readable files/executables' (like the aspx and such) from the 'read/writable' files.

ASP.NET Request - Can I get a posted file from a dynamic control created on client?

I have a web control with some custom javascript. The javascript creates new file upload controls on the client dynamically using code similar to:
var newFileUpload = document.createElement('input');
newFileUpload.type = 'file';
container.appendChild(newFileUpload); // where container is a div
This exists in an ASP.NET form with encType set to multipart/form-data. I will have 1 - n controls on the page (well, limited to a reasonable number, of course).
I now would like to capture the uploaded files in my ASP.NET application. Because of the approach taken above I know that I cannot capture them as I would from a FileUpload control (which unfortunately I cannot use). Is there another way to capture the uploaded files?
I have looked through a number of areas, including:
Request.Files
Request.Form
Request.Form.Keys
Request.InputStream
But I have not been able to find the content. I believe the client is submitting this data correctly but have been unable to determine what the server does with the raw request information (if this is even exposed).
Does anyone have any suggestions on areas I might further explore?
Thanks
You should add a unique name to your upload element to get it from Request.Form collection.
var newFileUpload = document.createElement('input');
newFileUpload.type = 'file';
//newFileUpload.id = 'file01';
newFileUpload.name = 'file01';
container.appendChild(newFileUpload);
EDIT : I tried id and name attibutes, the with name, you can get the content by
Request.Form["file01"]
Also if you should add the attribute below to your form element. This allows you to get the file content by Request.Files["file01"] :
enctype="multipart/form-data"

Resources