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
Related
I am trying to upload a word document to blob storage using C#. The code snippet is as below:
var blobServiceClient = new BlobServiceClient(connectionString);
var containerClient = blobServiceClient.GetBlobContainerClient(container);
containerClient.CreateIfNotExists(PublicAccessType.None);
var blobClient = containerClient.GetBlobClient(documentName);
using (var memoryStream = new MemoryStream({Binary of the File}))
{
var headers = new BlobHttpHeaders() { ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" };
await blobClient.UploadAsync(memoryStream, httpHeaders: headers).ConfigureAwait(false);
}
The document gets uploaded successfully to the Blob Storage. I can see that the content type is also being set properly while looking through Azure Storage Explorer. But, when i try to access this document (using document URL) through browser (chrome), it downloads the file as unknown file.
I tried the same by uploading a word document through Azure Storage Explorer. This file gets downloaded as word document while downloading it through browser.
Any idea what is going wrong?
As you see the figure below, the Content-Type header is stored as a property in the Blob Properties, so it will be set into the headers of the download response and then it will be recognized as a word file while download by browser.
So when you upload a word file, it's necessary to set the ContentType property for a blob via BlobBaseClient.SetHttpHeaders(BlobHttpHeaders, BlobRequestConditions, CancellationToken) Method or BlobBaseClient.SetHttpHeadersAsync(BlobHttpHeaders, BlobRequestConditions, CancellationToken) Method.
And then to write the Content-Typeheader of the headers of a download response with the value of contentType below by yourself on your server app.
Response<BlobProperties> response = await blobClient.GetPropertiesAsync();
var contentType = response.Value.ContentType
Or the download response from a blob url with sas token which headers default include the ContentType property as the Content-Type header.
I'm trying to convert current application that uses NPOI for creating xls document on the server to Azure hosted application. I have little experience with NPOI and Azure so 2 strikes right there. I have the app uploading the xls to Blob container however it is always blank (9 bytes). From what I understand NPOI uses filestream to write to the file so I just changed that to write to the blob container.
Here is what i think are the relevant portions:
internal void GenerateExcel(DataSet ds, int QuoteID, string ReportFileName)
{
string ExcelFileName = string.Format("{0}_{1}.xls",ReportFileName,QuoteID);
try
{
//these 2 strings will get deleted but left here for now to run side by side at the moment
string ReportDirectoryPath = HttpContext.Current.Server.MapPath(".") + "\\Reports";
if (!Directory.Exists(ReportDirectoryPath))
{
Directory.CreateDirectory(ReportDirectoryPath);
}
string ExcelReportFullPath = ReportDirectoryPath + "\\" + ExcelFileName;
if (File.Exists(ExcelReportFullPath))
{
File.Delete(ExcelReportFullPath);
}
// Create a new workbook.
var workbook = new HSSFWorkbook();
//Rest of the NPOI XLS rows cells etc. etc. all works fine when writing to disk////////////////
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve a reference to a container.
CloudBlobContainer container = blobClient.GetContainerReference("pricingappreports");
// Create the container if it doesn't already exist.
if (container.CreateIfNotExists())
{
container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
}
// Retrieve reference to a blob with the same name.
CloudBlockBlob blockBlob = container.GetBlockBlobReference(ExcelFileName);
// Write the output to a file on the server
String file = ExcelReportFullPath;
using (FileStream fs = new FileStream(file, FileMode.Create))
{
workbook.Write(fs);
fs.Close();
}
// Write the output to a file on Azure Storage
String Blobfile = ExcelFileName;
using (FileStream fs = new FileStream(Blobfile, FileMode.Create))
{
workbook.Write(fs);
blockBlob.UploadFromStream(fs);
fs.Close();
}
}
I'm uploading to the Blob and the file exists, why doesn't the data get written to the xls?
Any help would be appreciated.
Update: I think I found the problem. Doesn't look like you can write to a file in Blob Storage. Found this Blog which pretty much answers my questions: it doesn't use NPOI but the concept is the same. http://debugmode.net/2011/08/28/creating-and-updating-excel-file-in-windows-azure-web-role-using-open-xml-sdk/
Thanks
Can you install fiddler and check the request and the response packets? You may also need to seek back to 0 between two writes . So the correct code here could be to add the below before trying to write the stream to blob.
workbook.Write(fs);
fs.Seek(0, SeekOrigin.Begin);
blockBlob.UploadFromStream(fs);
fs.Close();
I also noticed that you are using String Blobfile = ExcelFileName instead of String Blobfile = ExcelReportFullPath.
My web application stores files (.png, .bmp, .jpg, .jpeg, .jpe, .jfif, .gif, .tif, .tiff, .doc, .docx, .pdf, .xls, .xlsx) in the app_data/upload folder. It gets stored on live server as it is on the local system. But when trying to download, it gets downloaded with the same file size but in the corrupted format.
Here is the code that downloads the file from the live server.
string strURL = "~/App_Data/Upload/" + fileRepository.FileName;
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.ContentType = "application/octet-stream";
response.AppendHeader("Content-Disposition", "attachment;filename=\"" + fileRepository.FileName + "\"");
byte[] data = req.DownloadData(Server.MapPath(strURL));
response.BinaryWrite(data);
response.TransmitFile(Server.MapPath(strURL));
FileRespository.DownloadCount(Convert.ToString(_fileID));
response.End();
Kindly find an image attached when word file is downloaded.
Please help me out.
Read the file as a blocks/buffers instead of transmit file.
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?
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);