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.
Related
I have XML content that I am retrieving from a service and I want to write it into a text file. I am getting this XML content in a string variable.
How can I read this and write in text file? Please help. I am getting data successfully using this code:
string results = "";
using (WebClient Web = new WebClient())
{
results = Web.DownloadString(WebString.ToString());
}
I have tried some links, but they are not helping
forums.asp.net
Reading-XML-File-and-Writing-it-to-txt-format-in-C
If you want to save it in a file, don't use DownloadString to start with - just use WebClient.DownloadFile.
If you really want to fetch it in memory and then save it, you can save it with:
File.WriteAllText(filename, results);
Note that this code doesn't depend on it being XML at all... nothing you're asking is XML-specific.
Long time lurker first time poster. Working with .Net / Linq for just a few years so I'm sure I'm missing something here. After countless hours of research I need help.
I based my code on a suggestion from https:http://damieng.com/blog/2010/01/11/linq-to-sql-tips-and-tricks-3
The following code currently saves a chosen file (pdf, doc, png, etc) which is stored in an sql database to the C:\temp. Works great. I want to take it one step further. Instead of saving it automatically to the c:\temp can I have the browser prompt so they can save it to their desired location.
{
var getFile = new myDataClass();
//retrieve attachment id from selected row
int attachmentId = Convert.ToInt32((this.gvAttachments.SelectedRow.Cells[1].Text));
//retrieve attachment information from dataclass (sql attachment table)
var results = from file in getFile.AttachmentsContents
where file.Attachment_Id == attachmentId
select file;
string writePath = #"c:\temp";
var myFile = results.First();
File.WriteAllBytes(Path.Combine(writePath, myFile.attach_Name), myFile.attach_Data.ToArray());
}
So instead of using File.WriteAllBytes can I instead take the data returned from my linq Query (myFile) and pass it into something that would prompt for the user to save the file instead?). Can this returned object be used with response.transmitfile? Thanks so much.
Just use the BinaryWrite(myFile.attach_Data.ToArray()) method to send the data since it is already in memory.
But first set headers appropriately, for example:
"Content-Disposition", "attachment; filename="+myFile.attach_Name
"Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Content-type guides the receiving system on how it should handle the file. Here are more MS Office content types. If they are known at the point the data is stored, the content-type should be stored, too.
Also, since the file content is the only data you want in the response, call Clear before and End after BinaryWrite.
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);
}
We have encountered this difference in file creation while using a HttpHandler Versus a Code Behind Aspx page.
We are reading a saved jpg/png picture as byte array from a 'Image' field in sql server database and create a physical file in the server.
Both the Aspx Page and Httphandler use the same code pasted below.
//Begin
int docID = Convert.ToInt32(Request.QueryString["DocID"]);
var docRow = documentDB.GetDocument(docID);
// Retrieve the physical directory path for the Uploads subdirectory
string destDir = Server.MapPath("../../Uploads").ToString() + "\\";
string strFileName = destDir + DateTime.Now.ToFileTime() + "_" + docRow.DocName.ToString();
FileStream fs = new FileStream(strFileName, FileMode.CreateNew, FileAccess.Write);
fs.Write(docRow.DocData, 0, docRow.DocData.Length);
fs.Flush();
fs.Close();
// End
After the file is created, it is viewable as a jpg/png Image only in Aspx Code Behind. While in case of HttpHandler it is not a valid Image.
Any ideas for this behavior/missing link/resolution steps will be helpful.
Thank you.
Finally isolating different steps the problem was identified to be the data being stored into Database Table.
The way to eliminate this issue was during upload of file, Create a physical file on the server local system. Read this file into a byte array and store into the Database Table. (Could be Encoding Issue)
Let's say I have a pdf form file available at website which is filled by the users and submitted to the server. On the server side (Asp.Net) I would like to merge the data that I receive in xml format with the empty pdf form that was filled and save it.
As I have found there are several possible ways of doing it:
Using pdf form created by adobe acrobat and filling it with itextsharp.
Using pdf form created by adobe acrobat and filling it with FDF Toolkit .net (which seems to be using itextsharp internally)
Usd pdfkt to fill the form.
Use pdf form file created with adobe livecycle and merge the data by using Form Data Integration Service
As I have no experience with this kind of task can you advise which option would be better/easier and give some additional tips?
Thank you in advance.
I would suggest using the 4th approach if possible because it would be cleaner. You would be using solutions specifically tailored for what you are asking to do, but if you don't have the available resources for such a solution I would suggest using the 1st option.
The 1st option is what I have recently dove into. I have found it relatively painless to implement.
Option 1 is possible if the following applies:
You have control of development of PDF forms.
You have control of formating xml data
You have can live with having uncompressed (fastweb=false) PDF files
Example of implementation:
Using Adobe Acrobat to generate a PDF form. Tip: Use Adobe Native Fonts when generating the forms. For each control you add that is not a native font it will import the font used and bloat the file when it is not compressed, and to my knowledge ITextSharp currently does not produce compressed PDFs.
Using ITextSharp Library to combine XML data with the PDF form to generate a populated document. Tip: to manually populate a PDF form from xml you must map xml values to control names in the PDF form and match them by page as shown in the example below.
using (MemoryStream stream = GeneratePDF(m_FormsPath, oXmlData))
{
byte[] bytes = stream.ToArray();
Response.ContentType = "application/pdf";
Response.BinaryWrite(bytes);
Response.End();
}
// <summary>
// This method combines pdf forms with xml data
// </summary>
// <param name="m_FormName">pdf form file path</param>
// <param name="oData">xml dataset</param>
// <returns>memory stream containing the pdf data</returns>
private MemoryStream GeneratePDF(string m_FormName, XmlDocument oData)
{
PdfReader pdfTemplate;
PdfStamper stamper;
PdfReader tempPDF;
Document doc;
MemoryStream msTemp;
PdfWriter pCopy;
MemoryStream msOutput = new MemoryStream();
pdfTemplate = new PdfReader(m_FormName);
doc = new Document();
pCopy = new PdfCopy(doc, msOutput);
pCopy.AddViewerPreference(PdfName.PICKTRAYBYPDFSIZE, new PdfBoolean(true));
pCopy.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
doc.Open();
for (int i = 1; i < pdfTemplate.NumberOfPages + 1; i++)
{
msTemp = new MemoryStream();
pdfTemplate = new PdfReader(m_FormName);
stamper = new PdfStamper(pdfTemplate, msTemp);
// map xml values to pdf form controls (element name = control name)
foreach (XmlElement oElem in oData.SelectNodes("/form/page" + i + "/*"))
{
stamper.AcroFields.SetField(oElem.Name, oElem.InnerText);
}
stamper.FormFlattening = true;
stamper.Close();
tempPDF = new PdfReader(msTemp.ToArray());
((PdfCopy)pCopy).AddPage(pCopy.GetImportedPage(tempPDF, i));
pCopy.FreeReader(tempPDF);
}
doc.Close();
return msOutput;
}
Save the File or post the file to the response of your ASP.Net page
Since you tagged this 'LiveCycle', I take it you have an installation of Adobe LiveCycle running somewhere (optionally, can install it somewhere).
In that case, I'd go for number 4 (with the modification of using the Adobe LiveCycle Forms ES module). The other three will undoubtedly yield compatibility issues in the long run. With the LiveCycle server (running the Forms module), you'll be able to handle any PDF, whether it's old, new, static, dynamic, compressed, Acrobat-based or LiveCycle-based.
You should be able to set things up, have the form send its data to the LiveCycle server, and use that data to populate the form. The fill can then be stored in the server's database, or routed into the PDF form (or any other form) and streamed back to the client.
Create the form using LiveCycle Designer.
The quick-and-dirty-option would be the following: Set the form to http-post (as for example an xfdf, see Acrobat for more info) to your ASP-server and publish it on the server (make sure your users don't download the form before opening it, otherwise this won't work. The form has to be opened in the web browser). Then simply capture the submissions as you would capture a http-post from a web page. Optionally, save the fill to a database. Then send the captured xfdf stream fill back to the client (could also be invoked at a later stage via a http-link). The xfdf stream will contain the URL of the form used to fill it out. The client web browser will ask the Acrobat/Adobe reader plug to handle the xfdf stream, and the plug will locate, download and populate the form pointed to by the xfdf.
The user should now be able to save the form AND it's fill - no Reader Extension needed!
You can also use iTextSharp to fill xml data into a Reader Extension enabled form. There are two things you need to set correctly:
Set PdfReader.unethicalreading = true to prevent BadPasswordException.
Set append mode in PdfStamper's constructor, otherwise the Adobe Reader Extensions signature becomes broken and Adobe Reader will display following message: "This document contained certain rights to enable special features in Adobe Reader. The document has been changed since it was created and these rights are no longer valid. Please contact the author for the original version of this document."
So all you need to do is this:
PdfReader.unethicalreading = true;
using (var pdfReader = new PdfReader("form.pdf"))
{
using (var outputStream = new FileStream("filled.pdf", FileMode.Create, FileAccess.Write))
{
using (var stamper = new iTextSharp.text.pdf.PdfStamper(pdfReader, outputStream, '\0', true))
{
stamper.AcroFields.Xfa.FillXfaForm("data.xml");
}
}
}
See How to fill XFA form using iText?