Create download link for static asset file - html

I would like to put a download link on my website so the users can download the file template.csv. The file is static and is located at the root of my /grails-app/assets folder.
Inside my page.gsp, I have tried 2 methods do so, to no avail :
Download the template
this results in a template.csv file being downloaded, but the content is the html code of page.gsp rather than the original content of the file I uploaded in my assets.
Download the template
the generated html file has a link to localhost:8080/mysite/assets/template.csv but clicking it prompts an error message : Failed - no file.
What is the correct way to do what I want to achieve ? Is there an issue with extra permissions I would need to add to allow the download of my file ?
Our webapp relies on a rather old technological stack :
Grails 2.3.4
Plugin asset-pipeline-2.2.5

I have had some troubles with downloading files straight with a -tag.
To overcome this, I use Controller method to return the file and place the downloadable files in their own folder under web-app/:
class MyController {
#Autowired()
AssetResourceLocator assetResourceLocator
def downloadExcelTemplate () {
String fileName = "MyExcelFile.xlsx"
/* Note: these files are found in /web-app/downloadable directory */
Resource resource = assetResourceLocator.findResourceForURI("/downloadable/$fileName")
response.setHeader "Content-disposition", "attachment; filename=${resource.filename}"
response.contentType = 'application/vnd.ms-excel'
response.outputStream << resource.inputStream.bytes
}
}
And just use regular a-tag to to link to this controller method.
This way you also gain more control over file downloads.

Related

How to insert a downloaded image into HTML code?

I'm a junior dev trying to build a portfolio site and want to upload a pic of me that is already downloaded on my PC. When I type in an src of an image that exists somewhere online it clearly appears on my live server but when I insert the src of an image existing somewhere within my PC's local drives it doesn't appear. Is it that I have to upload this image somewhere online (e.g. google drive) and then type in its new src or is there a way to upload offline images?
Hope someone can help!
Create a folder called assets in your project and add all images and any other files you may need. Then add the path to your image in src
there are some options to do it.
The more preferable is creating a folder let's say Src or Images. Then download any images into the folder using classes from a namespace System.IO (Path, Directory, ...). But be sure that your image names+extension are unique. Also, you can store in a DB file name and path the related file on your server and userId to be sure who added the file.
Another option is to store byte arrays in DB. Adding action for returning your file
public async Task<AcitonResult> GetImage(int id)
{
byte[] imgBytes = await GetImageFromDbById(id);
if (imgBytes == null)
return NotFound();
return File(imgBytes, "image/jpg");
}
Asking an image
<img src="/**YourControllerName**/GetImage/**#imageId**">

Unable to read json files in angular 5?

Hi I am developing web application in Angular 5. I am trying to read json file using http call as below. I am getting 404 error. Below is my service.ts file. Json file also remains in same folder so path may be correct.
public GetNodes() {
return this.http.get('./json1.json');
}
Below is my component code.
ngOnInit() {
this.nodeservice.GetNodes().subscribe(data =>
console.log(data)
);
I have done one work around and found my static files supposed to be in assets folder. I moved my json1.json to assets folder and I tried to access. Still I am getting same 404 error. Below is the full path where my json file kept
Projectname\ClientApp\app\components\Utilities
I am using ./json1.json because my service and json files are in the same folder utilities.
Can someone help me to figure it out the issue? Any help would be appreciated. Thank you.
To access any asset data like image or file, you need to put them in assets folder and access it from there as angular loads all the public data from assets folder so any asset will not be accessible from component's folder.
For file './json1.json' the URL will be HOST_Name/json1.json and it won't be there so better to put all files in assets folder and provide path for assets folder.
You can also change assets configuration in "angular.json" to point to your component's folder to access that json file.

UWP - How to read .jpg from Desktop inside of app

The functionality I am needing for my app is that if a user copies an image file (for example, a .jpg file in their Desktop folder), I need to extract that file from the clipboard and display it in my app.
I can already extract the storage file from the clipboard, and get the file path. But when I try to read the file path into a BitmapImage, I received a System.UnauthorizedAccessException error, because the image is not located in the app's folder.
It sounds like you are trying to open the file by path rather than directly using the StorageFile returned by the file picker.
Your app doesn't have direct access to most of the file system (including the downloads directories) and can access such files only indirectly via the file system broker. The StorageFile object works with the broker to open files the use had authorized and provides a stream of the files contents for the app to read and write to.
You can use Xamarin.Plugin.FilePicker or FilePicker-Plugin-for-Xamarin-and-Windows .
You may x:Bind path to XAML Image
<Image>
<Image.Source>
<BitmapImage UriSource="{x:Bind GetAbsoluteUri(Path)}"/>
</Image.Source>
</Image>
Code behind:
private Uri GetAbsoluteUri(string path)
{
return new Uri(Path.GetFullPath(path), UriKind.Absolute);
}
Try, hope it'll work :)

how to get browsed file location by user when he wants to download a file

this is my html code to make user to download a file and it is hitting controller
window.location.href="#routes.ListManagementController.downloadList("+listName+")?listname="+listName;
this is my controller code:
String listName = Form.form().bindFromRequest().get("listname");
response().setContentType("application/x-download");
response().setHeader("Content-disposition", "attachment;filename="+listName+"_data_export.csv");
The above two respose() statements make a pop up to download a file I want the browsed file location
File file = new File("C:/csv/" + filename);
So, using servlet api we can write the content into browsed file location using respose.getOutputStream() method. In play there are is no support for servlet. I want browsed file location selected by user so that i can give that location to File and write the file over there.
You can't get the location of a directory on the client, and even if you could, your server side could wouldn't be able to write to it (since it would usually be on a different computer).

Download files from folder with webmatrix

I have a folder created to get the files that users upload. However when i try to download the files, some extensions don't download.
I have this code to list all files that are in the folder, i can see all the files with no problem.
#foreach (string fullFilePath in Directory.GetFiles(Path.Combine(Server.MapPath("~/uploadedFiles"),"Ticket Id - "+#id)))
{
<div class="linkFicheiros">#Path.GetFileName(fullFilePath)</div>
}
With this line
#Path.GetFileName(fullFilePath)
i can download files with extension: ".zip" , ".xls" but extensions like ".msg"(sometimes users need to upload this extension) i got an error "The page cannot be found". Even ".jpg" instead of downloading the file it opens the image on the browser.
I think that is something how i'm trying to reach the file, but i can't get to a solution.
Any thoughts ?
The browser would try to always view the content of the file. If its an Image file like .jng etc. But if there is a .zip file, it would let the user download and open it. Because browser can't open it.
You need to push the file to the user. For that you can try the following code:
var file = Server.MapPath("~/images/" + Request["img"]);
Response.AppendHeader(
"content-disposition", "attachment; filename=" +
Request["img"]);
Response.ContentType = "application/octet-stream";
Response.TransmitFile(file);
Now, you can see that in the code I am sharing, the file is a variable, which is being pointed to the file in the File System. Please note that there is a Query String parameter, which would be sent alongwith the URL, for example:
Download Image
Now the header would be appened, and the
Request.ContentType = "application/octet-stream"
is used to force the browser to show the Dialoug of Open/Save.
Then the transmit file to download it.
To only execute the code when needed
To only execute that download code block, you need to set the value in a block for condition to be true. For example, you can use a parameter to check whether to download the file or not. Try something simple like,
<a href="~/download_file/image_link.png?download=true>Download</a>
Then on the code behind use this:
var download = Request.QueryString["download"];
if(download == "true") {
/* place the code here */
}
Now it would only execute if the condition is true, otherwise it would skip that part.