Temporary folder for attachments - xpages

What is the best place to put some temporary files that will become attachments later(by means of embedObject)? Are there any temporary folders for xpages that can be obtained and used for this purpose?
Or is there a way to create atachments from stream without use of intermediary files?

You can do something like this with the MIMEEntity. Then you will be able to stream an attachment right into your notesdocument. You will have to get a handle to a notesdocument and an outputstream with the file content. Then you can try to do something like I have done in the code snippet here.
MIMEEntity m = newDoc.createMIMEEntity( fieldNameForFiles );
MIMEHeader header = m.createHeader("content-disposition");
header.setHeaderVal("attachment;filename=\"" + this.getFileName() + "\"");
Stream oStream = session.createStream();
InputStream is = new ByteArrayInputStream( ((ByteArrayOutputStream)outStream).toByteArray() );
oStream.setContents(is);
m.setContentFromBytes(oStream, "application/pdf", MIMEEntity.ENC_IDENTITY_BINARY);
m.decodeContent();
newDoc.save(true, true);

Related

How to save file from HTML2PDFRocket to folder on Server

My Azure Web app calls html2pdfrocket with this code:
MemoryStream stream = new MemoryStream(result.Content.ReadAsByteArrayAsync().Result);
System.IO.File.WriteAllText(path, stream.ToString());
But I get back an invalid PDF of just a few bytes. I know the URL I pass to html2pdfrocket is valid because I can paste it into their Website to test it. Do I need to async/await or something else to get all the data before attempting to save it to a folder?
No need to use async/await, the .Result does the thing like await.
A similar error in your code, stream.ToString() only converts the stream object itself to a string, but does not contain the content.
I suggest you use byte[] array instead of stream(I did test with stream, but the saved .pdf file is empty even though the content length is correct).
Try use byte[] array like below, and it works at my side:
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("apikey","xxxxx"),
new KeyValuePair<string, string>("value", "the url")
});
var result = client.PostAsync("http://api.html2pdfrocket.com/pdf", content).Result;
if (result.IsSuccessStatusCode)
{
// change the path as per your need
System.IO.File.WriteAllBytes(#"d:\temp\0618.pdf", result.Content.ReadAsByteArrayAsync().Result);
}
}

How to get the filename and path from an upload control in xpages

I have a document that the user attaches a file to an upload control called licenseKey. In a SSJS I need to retrieve the content of that file and process it. I know that it is a ASCII text file and I know the general format. I would like to create var inStream:NotesStream for the content of the attachment, but I can't see how to do this in SSJS.
I have tried using getComponent("licenseKey") but don't see what might be next.
This code would actually be run by the user that attaches the file, so the local File Path and File Name would be valid if I could get them from the upLoad Control.
Thanks.
Julian Buss did a nice explanation
here. Quote:
How to process an uploaded file
Place code like this in the beforeRenderResponse event of an XPage to
get a handle to a just-uploaded file:
var con = facesContext.getExternalContext();
var request:com.sun.faces.context.MyHttpServletRequestWrapper = con.getRequest();
var map:java.util.Map = request.getParameterMap();
var fileDataName = "file"; //name of the POST request parameter that contains the file
var fileData:com.ibm.xsp.http.UploadedFile = map.get( fileDataName );
var tempFile:java.io.File = fileData.getServerFile();
The file is in the "xspupload" directory on the Domino Server and has
some crypting filename. You can get the original filename with
fileData.getClientFileName().
For example, you can attach the file to some Notes document with code
like this:
var correctedFile = new java.io.File( tempFile.getParentFile().getAbsolutePath() + java.io.File.separator +
fileData.getClientFileName() );
var success = tempFile.renameTo(correctedFile); //rtFiles is a rich text item on a notesdocument of your chosing
rtFiles.embedObject(lotus.domino.local.EmbeddedObject.EMBED_ATTACHMENT,
"", correctedFile.getAbsolutePath(), null);
correctedFile.renameTo(tempFile);
This snippet renames the temporary file to the orginal filename,
attaches it to a RichText item and renames it back to the cryptic name
(so that it will be deleted by Domino after processing).
Try this in beforerenderResponse:
var fileData:com.ibm.xsp.http.UploadedFile = facesContext.getExternalContext().getRequest().getParameterMap().get(getClientId('fileUpload1'));
if (fileData != null) {
var tempFile:java.io.File = fileData.getServerFile();
...

How to open save as dialog box for downloading from cloud

I'm making project which includes downloading files from cloud(Azure) storage. I want to open save as dialog box but not getting it . I used following code.
enter code here // Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob1");
string FileName = "a3.jpg";
string Filename = FileName.Substring(0, FileName.LastIndexOf("."));``
Response.AppendHeader("Content-Disposition", "attachment; filename=" FileName);
Response.TransmitFile(Server.MapPath("~/blockBlob/myblob1/" + Filename));
Response.End();
/* to download file from cloud
using(var fileStream =System.IO.File.OpenWrite(#"C:\Users\prak\Pictures\ppp.JPG"))
{
blockBlob.DownloadToStream(fileStream);
Response.Write("");
Response.Write("Succefully downloaded!");
}*/
please help...
thanks in advance
You will need to redirect your form to an ashx handler that writes the file content directly into the output stream. This is not specific to Azure, although if the file is being accessed from a blob it may need to be moved temporarily to the web server so you can reference the local path in the "attachment;filename".
Response.Clear();
Response.ContentType = "image/jpeg";
Response.AddHeader( "Content-Disposition", "attachment;filename=\"myfile.jpg\"" );
// write file data to output stream here
Response.End();
Another method is to use HttpWebRequest as described in the following post:
Download/Stream file from URL - asp.net

the file you are trying to open is in a different format than specified by the file extension in Asp.Net

the file you are trying to open is in a different format than specified by the file extension c# error when trying to open file in excel.
Here is my code
public ActionResult Export(string filterBy)
{
MemoryStream output = new MemoryStream();
StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
var data = City.GetAll().Select(o => new
{
CountryName = o.CountryName,
StateName = o.StateName,
o.City.Name,
Title = o.City.STDCode
}).ToList();
var grid = new GridView { DataSource = data };
grid.DataBind();
var htw = new HtmlTextWriter(writer);
grid.RenderControl(htw);
writer.Flush();
output.Position = 0;
return File(output, "application/vnd.ms-excel", "test.xls");
}
when am trying to open excel i get this error
the file you are trying to open is in a different format than
specified by the file extension
After clicking on Yes the file open properly. but i don't want this msg to appear.
I have used CloseXML to solve the problem.
public static void ExportToExcel(IEnumerable<dynamic> data, string sheetName)
{
XLWorkbook wb = new XLWorkbook();
var ws = wb.Worksheets.Add(sheetName);
ws.Cell(2, 1).InsertTable(data);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", String.Format(#"attachment;filename={0}.xlsx",sheetName.Replace(" ","_")));
using (MemoryStream memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
memoryStream.Close();
}
HttpContext.Current.Response.End();
}
Installed ClosedXML in my project using Nuget Package Manager.
the file you are trying to open is in a different format than
specified by the file extension
You are constantly getting that warning message because the file that got created is not an actual excel file. If you will look into the generated file, it's just a bunch of html tags. Remember that a GridView's RenderControl will generate an html table.
To fix your issue, you need to either use a third party tool that creates a real excel file (one tool you might want to use is NPOI) or create a comma-delimited file, or simply a csv file, and return that file.
In case someone else stumbles across this... I needed to convert blobs back into files on-the-fly in C#. Pdf's worked well and excel gave me this same error as OP explains.
This is the code I wrote which handles excel differently from other file types.
Giving excel application/octet-stream with an actual filename solved my issue. Probably not the cleanest way to do it but it was good enough for my purposes.
string theExt = Path.GetExtension(theDoc.documentFileName).ToUpper();
Response.Clear();
if (theExt == ".XLS" || theExt == ".XLSX"){
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", string.Format("inline; filename={0}", theDoc.documentFileName));
}
else{
Response.ContentType = theDoc.documentMimeType;
Response.AddHeader("Content-Disposition", string.Format("inline; filename={0}", theDoc.documentTitle));
}
using (MemoryStream stream = new MemoryStream(theDoc.file))
{
stream.WriteTo(Response.OutputStream);
stream.Close();
};
Response.End();
In case someone needs to export a dataset as excel file with CloseXML.
Dataset ds = { your data from db }
var xlsx = new XLWorkbook();
var dataTable = ds.Tables[0];
xlsx.Worksheets.Add(dataTable);
xlsx.SaveAs("export.xlsx");

Open secure Sharepoint file programmatically using c#

I need help opening am online Sharepoint file programmatically. These files need to be secured on Sharepoint (so that users can't wander into them), but I also need to access it somehow using my webpart (which will check for security). Normally, you can just use a hyperlink that links to the Sharepoint file, but we don't want people sharing these hyperlinks, so that won't work.
I want the user to click a link, and have them see the "Open, Save, Close" dialog menu for that file.
I have tried this
String fileName = #"file.txt";
String filePath = #"~online filePath/";
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearHeaders();
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
//or whatever file type, I can code that later
response.AddHeader("Content-Disposition", "attachment; Filename=" + fileName + ";");
response.TransmitFile(filePath + fileName);
//response.Flush();
response.End();
Unfortunately, while this works fine for local files (C://...), when I try this on my web fike, I only receive a text document that has the source code for the current page. Not sure why.
As for dealing with the permissions, I plan to use elevated priviledges to have the program gain access to the files.
I would appreciate any help, Thanks.
Here is sample code to provide a file for download with SharePoint
using (SPWeb web = SPContext.Current.Web)
{
//Get fileName and filePath here
response.AddHeader("Content-disposition", "attachment; filename=" + fileName);
response.ContentType = "application/octet-stream";
SPFile file = web.GetFile(filePath);
byte[] fileBytes = file.OpenBinary();
response.OutputStream.Write(fileBytes, 0, fileBytes.Length);
response.End();
}
Does this help or are you having problems locating the fileName and filePath?

Resources