Reputation: 29573
How can i populate dropdown lists with list of files in a folder and then when a user clicks on the name of the file they download it?
$(document).ready(function () {
$("#2").empty();
$("#3").empty();
$("#4").empty();
$btn1.hide();
$.ajax({
url: '/uploads/docs/' + "name" + ".pdf",
type: 'HEAD',
error: function () {
},
success: function () {
e.preventDefault();
window.location.href = '/uploads/docs/' + "name" + ".pdf";
}
});
});
I have got this which can look in a folder but only for one pdf name and if it exists it downloads a download a pdf. But how do i populate the dropdown and use that? I need to have the user be able to donwload any sort of file .jps .exe etc thanks
Upvotes: 1
Views: 4179
Reputation: 617
I think easiest way to do this is create a model with properties File Name & File Path.(or you can use anonymous type with these properties)
public class File
{
public string FileName { get; set; }
public string FilePath { get; set; }
}
create a file collection using your data in Controler
ViewBag.FileCollection = "your file collection";
then in your view use Html.DropDownList:
@Html.DropDownList("Files", new SelectList(ViewBag.FileCollection, "FilePath", "FileName"))
Nicola Peluchetti's answer has the client side code.
Upvotes: 1
Reputation: 2114
If the contents of the directory is going to be changing often, you'll definitely have to do some work on the server side.
Using PHP, you'd create a script which first reads all the files in a directory using opendir()
and readdir()
. You'll probably want to read all the files in the directory into an array, and then sort them alphabetically using sort()
, since they won't come in an alphabetical order. Then the script outputs the file list in HTML - for example, using a <table>
or <ul>
, where you can put standard file download links (<a>
tags).
The output of the PHP file is then loaded using AJAX, and inserted into the page.
$.ajax(
{
url:'/uploads/ajax.php',
success: function(d) { $("#filelist-container").html(d) }
}
);
Upvotes: 0
Reputation: 76900
You could do
<select id=yourSelect>
<option value="">Choose a file</option>
<option>File1</option>
<option>File2</option>
<option>File3</option>
</select>
$('#yourSelect').change(function() {
var name = this.value;
if (name !== "") {
if (confirm("Are you sure you want to download " + name)) {
$.ajax({
url: '/uploads/docs/' + name + ".pdf",
type: 'HEAD',
error: function() {},
success: function() {
e.preventDefault();
window.location.href = '/uploads/docs/' + name + ".pdf";
}
});
}
}
});
Fiddle here. http://jsfiddle.net/G4wJV/
This tries to download /uploads/docs/File1.pdf
when you choose the first option and so on
Upvotes: 1