Provide static file download at server in web application - asp.net-mvc-4

I am working on an MVC 4 web application. On one page I am providing an anchor link which refers to a file on application's directory. The code of the same is -
#Html.Action("Download_Static_File", "Charge_Entry", new { File_Path = "../../Content/Templates/Pt_Data/Pt_Data.xls", File_Name = "Pt_Data_Template", value = "Download template" });
My motive is that the file should be downloaded on click.
However when I click the link, I get an error like
Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\Content\Templates\Pt_Data\Pt_Data.xls'.'
I also tried
System.Web.HttpContext.Current.Server.MapPath
which is giving this error:
OutputStream is not available when a custom TextWriter is used.
The action method being called is:
public FileResult Download_Static_File(string File_Path,string File_Name)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(File_Path);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, File_Name);
}
Is it the correct approach? Any help will be appreciated.
I also referred this link

Your anchor seem to be pointing to a controller action named Download_Static_File (which unfortunately you haven't shown) and passing a parameter called File_Path.
The #Html.Action helper that you are using in your view is attempting to execute the specified action as a child action. You may find the following blog post useful which describes child actions: http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx/
I guess that what you are trying to achieve is to generate an anchor in your view pointing to the static file which can be downloaded by the user. In this case you'd rather use an anchor tag in conjunction with the Url.Action helper:
<a href="#Url.Content("~/Content/Templates/Pt_Data/Pt_Data.xls")">
Download_Static_File
</a>
This assumes that your web application has a folder called Content/Templates/Pt_Data under the root containing a file named Pt_Data.xls which will be downloaded by the user when he clicks upon this anchor tag.
If on the other hand the file that you want to be downloaded by the user is situated in a folder which is not publicly accessible from the client (for example the ~/App_Data folder) you might in this case have a controller action on your server that will stream the file:
public ActionResult DownloadStaticFile(string filename)
{
string path = Server.MapPath("~/App_Data");
string file = Path.Combine(path, filename);
file = Path.GetFullPath(file);
if (!file.StartsWith(path))
{
throw new HttpException(403, "Forbidden");
}
return File(file, "application/pdf");
}
and then in your view you would have an anchor to this controller action:
#Html.ActionLink(
linkText: "Download template",
actionName: "DownloadStaticFile",
controllerName: "Charge_Entry",
routeValues: new { filename = "Pt_Data.xls" },
htmlAttributes: null
)

Related

how can I show the pdf file content inside from razor file

I created a document file from word and has exported as pdf . i want to show the pdf content inside the Div element in razor page. How can I show the pdf content from razor page. Please can you provide an example code how to show in blazor server side
If you stored your pdf file directly in your documents for example in the folder wwwroot/pdf.
wwwroot/pdf/test.pdf
You can display this PDF with this line of html bellow :
< embed src="pdf/test.pdf" style="width=100%; height=2100px;" />
It will provide you a pdf displayer with printing options !
If you want to go further, upload your file and then display it, I will recommend you to go check this explanation :
https://www.learmoreseekmore.com/2020/10/blazor-webassembly-fileupload.html
The upload for PDF files works the same as Img file, you need to go check IBrowserFile documentation.
You will see that it has a Size obj and a OpenReadStream() function that will help you get the display Url for your file (image or pdf)
If the site abow closes, this is the upload code that is shown on it :
#code{
List<string> imgUrls = new List<string>();
private async Task OnFileSelection(InputFileChangeEventArgs e)
{
foreach (IBrowserFile imgFile in e.GetMultipleFiles(5))
{
var buffers = new byte[imgFile.Size];
await imgFile.OpenReadStream().ReadAsync(buffers);
string imageType = imgFile.ContentType;
string imgUrl = $"data:{imageType};base64,{Convert.ToBase64String(buffers)}";
imgUrls.Add(imgUrl);
}
}
}
This code was written by Naveen Bommidi, author of the blog where I found this usefull code
If you want, as I said, upload a PDF and then display it.
You can use the same html line :
< embed src="#imgUrl" style="width=100%; height=2100px;" />
And your uploaded files will be displaying.
Example

GWT Image Upload empty content

I am trying to implement GWT image upload functionality. I have made the required code change but for some reason upload is not happening. At the server side the image is not being received. So I checked at the client side (browser) the request header and content and then I found that Content-Length: 44 (just 44). Then I realized that the image is not being sent to server on from submission. Please check the below GWT code.
VerticalPanel vp = new VerticalPanel();
vp.add(CommonFormLayoutUtil.createLabel("Upload"));
final FormPanel form = new FormPanel();
form.setAction("CGIImageUpload");
// set form to use the POST method, and multipart MIME encoding.
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
final FileUpload fileUpload = new FileUpload();
Button uploadButton = new Button("Upload");
uploadButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
//get the filename to be uploaded
String filename = fileUpload.getFilename();
if (filename.length() == 0) {
showError("No File Specified!", null);
} else {
//submit the form
form.submit();
}
}
});
vp.add(fileUpload);
vp.add(uploadButton);
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
// When the form submission is successfully completed, this
//event is fired. Assuming the service returned a response
//of type text/html, we can get the result text here
showError(event.getResults(), null);
}
});
form.add(vp);
Am i missing anything here? Please suggest.
Thanks.
FormPanel states the following:
"This panel can be used to achieve interoperability with servers that accept traditional HTML form encoding. The following widgets (those that implement com.google.gwt.user.client.ui.HasName) will be submitted to the server if they are contained within this panel" (emphasis mine)
You need to set the name of the FileUpload widget otherwise it will not be submitted by the FormPanel.
fileUpload.setName("someName");
Try setting this and it should work

Open specific folder in folder tree (IBM Content Navigator)

I'm developing a IBM Content Navigator plugin, which allows me to open a selected folder from the search feature in the browse feature. The plugin action contains the following code:
// Variable contentItem is provided by Content Navigator when executing the plugin action.
let layout = ecm.model.desktop.layoutDijit;
let browsePaneMenuItem = layout.launchBarContainer.getMenuItemByID("browsePane");
layout.launchBarContainer._menuItemClick(browsePaneMenuItem, false);
layout.mainPane = layout.launchBarContainer._panels["browsePane"];
layout.mainPane.folderTree._tree._selectItem(contentItem);
This code switches the feature and opens the content of the selected folder (contentItem) as the result set in the center panel. However, the folder tree does not open the item at the specific location. To do that, I've tried the following code:
let repo = layout.mainPane.repository;
let parentItemDocId = contentItem.attributes.Parent;
let parentItemTemplate = parentItemDocId.split(',')[0] || null;
repo.retrieveItem(parentItemDocId, function(item) {
contentItem.parent = item;
layout.mainPane.folderTree._tree._selectItem(item);
console.debug('parents parent: ' + item.parent);
}, parentItemTemplate, "current", null, contentItem.objectStoreId, "", null);
The item.parent property in console.debug is undefined, when I call retrieveItem on the repository object.
The contentItem.parent property points to the search, in which the item is being shown. However, contentItem.attributes.Parent is the docid of the actual parent folder. I suspect, Content Navigator can't open the folder, because the contentItem's parent is not the same item in search feature as in the browse feature.
How can I open the specific folder in the folder tree?
To open a specific folder on a Folder Tree all you need to do is create an array of ids with the path of the folders from the root folder to the folder you want to open (you can see the Dossier example in the redbooks to see how to loop subfolders on the server side).
Then run the below js code, when path is an array of objects with id: (starting with the root folder and ending with the selected folder)
var myPaths = [];
myPaths.push(path);
this.folderTree._tree.set('paths', myPaths);

Display string in xml format in browser either using view or controller

I have a string in my model.The string is actually XML content. I have a link on my page, when clicked it opens a new tab and displays the text as XML.
The result should be the same as when I right click on an xml file and open with Internet Explorer. The difference is that this is no file, its text that I need to display as XML in a new tab.
Anyone have an idea how to achieve this without creating a file and without giving a path to a file.
You could have a controller that will serve this XML and set the proper content type header:
public class MyXMLController: Controller
{
public ActionResult Index()
{
MyModel model = GetModelFromSomewhere(...);
return Content(model.StringPropertyContainingXML, "text/xml");
}
}
now all that's left is to write an anchor link pointing to /myxml/index:
#Html.ActionLink("Click to open XML", "index", "myxml", null, new { _target = "blank" })

Load local HTML into WebView

Can I load a local HTML file (with images and ...) into a WebView?
Just setting the Source parameter does not do the trick.
You can load it from a file as long as the file is part of the app package, e.g.:
WebView2.Source = new Uri("ms-appx-web:///assets/text.html");
From WebView.Navigate
WebView can load content from the application’s package using
ms-appx-web://, from the network using http/https, or from a string
using NavigateToString. It cannot load content from the application’s
data storage. To access the intranet, the corresponding capability
must be turned on in the application manifest.
For a 'random' file, I suppose you could prompt user via file picker to select the file then read it into a string and use NavigateToString, but the user experience there may be a bit odd depending on what you're trying to accomplish.
I was working at this problem for a long time and I found a way to do that:
At first you should save it in InstalledLocation folder. If you haven't option to create a new .html file you can just use file.CopyAsync(htmlFolder, fname + ".html");
Look into my example:
StorageFolder htmlFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.CreateFolderAsync(#"HtmlFiles", CreationCollisionOption.GenerateUniqueName);
IStorageFile file = await htmlFolder .CreateFileAsync(fname + ".html", CreationCollisionOption.GenerateUniqueName);
and than you can easily open your .html file:
var fop = new FileOpenPicker();
fop.FileTypeFilter.Add(".html");
var file = await fop.PickSingleFileAsync();
if (file != null)
{
string myPath = file.Path.Substring(file.Path.IndexOf("HtmlFiles"));
myWebview.Navigate(new Uri("ms-appx-web:///" + myPath));
}
Remember just only from InstalledLocation you can open it with ms-appx-web:///