Get HTML input file dialog result - javascript

I've been trying add an image uploader for my website, and I have already written the uploader method in asp.net mvc. Since I don't want to have two buttons in my page (one for browse and one for upload) I decided to write another function using JQuery to handle it. At this point I've face the problem of having to know the <input type="file />" dialog result to run my uploader.
My question is that, is it possible to detect the user's choice (Open/Cancel) in JQuery ?
My code looks like this :
#using (HTML.BeginForm ("Upload", "SomeController", FormMethod.Post, new { enctype = "multipart/form-data" }))
<input type="file" name="file" id="file" class="Hidden" />
<input type="submit" id="upload" class="Hidden" />
}
<button id="UploadIt">Image</button>
and the java script:
$('#UploadIt').click(function() {
$('#file').trigger("clcik");
//now if (dialog result is Open) {$('#upload').trigger("click");}
// else {Do Nothing}
});

After reading the change() event documentation (dandavis mentioned it in the comment), I managed to fix the problem. However I decided to share my solution in case anyone faces the same issue.
$('#UploadIt').click(function () {
$('#file').trigger("click");
$(":file").change(function () {
if (this.files[0].size > 0) { Upload(); }
else { }
});
});

Related

How to get values of input type file in angularjs?

I am creating simple application in angularjs using slim framework. In that, I am creating form for some data like name, categories, currency and Image file etc. In this app, I am having trouble with input type file. I can get all the data of textbox or radio button etc but I can't get data of input type file. Below is the code for that.
index.html :- HTML file
<form method="POST" enctype="multipart/form-data" class="form account-form" name="form" ng-submit="creator(user)" role="form">
<input type="text" name="name" ng-model="user.name" />
<input type="radio" name="category" ng-model="user.category" value="Science" >
<input type="radio" name="category" ng-model="user.category" value="Engineerig" >
<input type="file" ng-model="user.image_file" name="image_file">
</form>
registerController.js :- Controller file
app.controller('CreatorController', function($scope,$rootScope,$location,$http,CreatorService,FlashService) {
$scope.creator = function (user) {
// alert("create");
$scope.dataLoading = true;
CreatorService.creator(user)
.then(function (response) {
if(response.data['message']){
FlashService.Success('Registration successful', true);
$location.path('/crete-page');
} else {
FlashService.Error('Registration failed');
}
});
}
});
registerDB.php :- DB handler PHP file in slim framework dir
<?php
function insertUser($data) {
print_r($data); //Getting All data here from form but not getting File values
}
?>
If you want to send it to a server you can't just receive the file and send it, sometimes you have to transform it in a blob or something.
I found this fiddle
don't know if it works but you can try. (stupid stackoverflow makes me put code after a fiddle link, wtf!)
Or else you can use angular-file-upload, at least was what I used when I tried to do something like that. But I was using nodejs on the server and even on server I had to receive using another library specific for the situation. Dunno how it works with php.
GL!
This may be old question but i came across same problem and this is how i fixed it.
add this code to registerController.js
function getPath() {
$('#filePath ').on('change',function ()
{
var filePath = $(this).val();
$scope.fileURL = filePath;
});
}
getPath();
$scope.fileURL will then hold the data/value for the input file. you can then set user.image_file to be this value "$scope.fileURL"
and your html should be
<input id="filePath " type="file" ng-model="user.image_file" name="image_file">
hope this helps

Is it possible to have a progress bar on the client side linked to the progress of saveAs()?

I have a controller for uploading a file of any type. A condensed version of it is
[HttpPost]
public ActionResult Index (HttpPostedFileBase file, string selectedOrgName, string selectedCatName, string previouslyUploadedFilesJSON = null)
{
// ...... bunch of stuff
try
{
file.SaveAs(newFileServerPathAndName); // Saves file with new file name in assets folder
}
catch
{
throw new Exception("Error when trying to save file to Assets folder.");
}
// ... bunch of other stuff
return View();
}
and the model is like
#using (Html.BeginForm("Index",
"FileUpload",
FormMethod.Post,
new { enctype = "multipart/form-data", #id ="upload-file-form"}))
{
<div>
<label for="file">Upload File:</label>
<input type="file" name="file" id="file" /><br>
<input type="submit" value="Upload" /><img class="loading-icon hidden" src="/ClientPortal/images/loadinggif.gif"/>
<input type="hidden" name="selectedOrgName" class="selectedOrgInput" />
<input type="hidden" name="selectedCatName" id="selectedCatInput"/>
<input type="hidden" name="previouslyUploadedFilesJSON" value="#ViewBag.uploadedFilesJSON" />
<br><br>
</div>
}
and what I'm wondering is whether it's possible for me to have a progress bar on the client's side that is linked to the progress of the saveAs function. In Google Chrome there is already something on the bottom of the browser window like
Uploading (31%)
when uploading the file, so there must be some way to tap into that number on the client side, or there must be some other way using the controller.
The easiest solution is to do this in the browser, since it obviously knows how much data has been sent. Your controller isn't invoked until the upload is complete, so that won't do it, and even if you had the data on the server side then you have to work out how to get the data back to the browser.
jQuery has some support for this, e.g. File upload progress bar with jQuery
You should look into SignalR. We just implemented a progress bar for file uploads in an MVC application and it works great. It's really easy to implement and there are countless tutorials and samples on the web that will show you how to wire it up.

HTML Link that does POST (using Dojo)

I am new to web development so help is much appreciated!
I need to create a link in a form that will go to a separate window - the tricky part is that the link needs to be a POST request with arguments in this format (p_guid=55555555&f_name=someName&...) to a URL provided to me.
I'm using html + Dojo and have a link created:
HTML:
Identity Lookup Tool
In Dojo:
on(identityLookup, "click", function(evt) {
console.log("Post will go here 1");
// TODO
});
How can I get this pop up with a new window and do a post request to the URL?
Try embedding your POST parameters in a hidden form. Something like below.
<form id="myform" action="some_url_here" method="post" target="_blank">
<input type="hidden" name="p_guid" value="55555555" />
<input type="hidden" name="f_name" value="someName" />
</form>
Then when the link is clicked do something like:
dojo.byId("myform").submit();
This should submit the form against a new window because of the target="_blank" attribute on the form tag.
you can use dojo/request
on(identityLookup, "click", function(evt) {
console.log("Post will go here 1");
var request = require("dojo/request");
var promise = request.post("url", {
data: { "p_guid": 55555555, "f_name":"someName" },
handleAs: "json"
});
});

Link to current window within a JavaScript function

folks!
I'm an absolute beginner in JavaScript and I'm trying to get a specific condition within a JavaScript function (passwd=="eggplant) to open a link in the same window. I've tried the "window.location.href" (currently on the code), "window.location" and "location" objects, as well as the "window.location.replace()" function, but they didn't work. I should also point out that I'm using a separate .js file to write the scripts.
Here's the whole function:
function colorFunc()
{
var passwd = document.getElementById("pass").value;
if(passwd=="614051"){
window.open ('color1.html')
}
else if(passwd=="eggplant" || passwd=="Eggplant" || passwd=="EGGPLANT"){
window.location.href = 'color2.html';
}
else{
alert('You have got the answer wrong!');
}
}
All the other conditions work, and I could even open "color2.html" using "window.open". Could you, more experienced users, please tell me what I'm doing wrong?
Edit:
Here's the relevant portion of my .html file.
<form name="input">
<input id="pass" name="Answer" placeholder="Your answer"></input>
<input type="submit" value="Submit" onclick="colorFunc()"></input>
</form>
Thank you very much!
(DEMO HERE)
Use this on your html onclick:
onclick="colorFunc(this)"
and then inside your javascript function colorFunc(e) add e.preventDefault; to prevent from submiting the form. You don't need to use a form for this behavour you show here, but maybe you need it for other code. Anyway this should work.
HTML
<input id="pass" name="Answer" value="614051" placeholder="Your answer"></input>
<button type="button" value="Submit" onclick="colorFunc(this)">Send</button>
JS
function colorFunc(e)
{
var passwd = document.getElementById("pass").value;
if(passwd=="614051"){
window.open ('color1.html','_self'))
}
else if(passwd=="eggplant" || passwd=="Eggplant" || passwd=="EGGPLANT"){
window.open('color2.html','_self'));
}
else{
alert('You have got the answer wrong!');
}
}

Html file picker with jQuery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reading client side text file using Javascript
I want to open a txt file at client, parse it with javascript and post parsed data to a server page with ajax. I have scripts for parsing and posting. All i need now is to simply pick file from client computer.
What I need is something like this:
<div id="content">
<button id="selectFile" onclick="return selectFileClick();" />
</div>
When user clicks button, a file dialog box appears and returns selected file. With this file name, I will make other operations like parsing etc.
function selectFileClick()
{
var fileName = filedialog();
// parsing file...
return false;
}
Edit: I dont want to upload file and I have a custom design which doesnt look like;
<input type="file" id="file">
I need something like this: jquery file dialog plugin
Edit (2): I solved issue by this way;
$(function () {
$("#button1").click(function (event) {
event.preventDefault();
$('#file').trigger('click');
});
document.getElementById('file').addEventListener('change', readFile, false);
});
at html;
<input id="button1" type="submit" value="add" />
<input type="file" id="file" style="display: none">
I hope this helps someone else ;)
Have a look at this: HTML File API
That would probably be the easiest way to do it, e.g.
<input type="file" id="file">
Then just attach a function to the "onChange" function of the element.
EDIT: Just noticed that you're using jQuery, so you could really just do:
$("#file").change(function() { selectFileClick(); });

Categories