Implementing progress .gif beside upload button - javascript

I have an upload button on my MVC web application which allows a user to upload a file. This file is uploaded onto the system and some async actions are made on this file which may take up to 1/2 minutes. I would like show processing.gif when the users presses the upload button and then hide the .gif when the async actions have finished i.e. when "return View();" has occurred from the HttpPost Upload controller. Can anyone tell me the easiest way to implement this please? I have been messing around with it and can not get it to work correctly. The processing.gif image is currently hidden as you can see from the below code:
The Upload View:
<h4><strong>Upload Survey</strong></h4>
<div>
<p><strong>Upload Surveys in .PDF format</strong></p>
<br />
<form class="btn btn-default" method="post" enctype="multipart/form-data" action="#Url.Action("Upload", "CompletedCamps")">
<div>
<input name="file" type="file" class="btn btn-link" required />
<br />
<button type="submit" class="btn btn-block btn-primary">Import</button>
</div>
</form><img id="loading" src="../../Content/processing.gif" alt="Updating ..." style="display:none" />
</div>
<br />
The Upload Controllers:
[HttpGet]
public ActionResult Upload(int? id)
{
CompletedCamp completedCamp = db.CompletedCamps.Find(id);
return View(completedCamp);
}
[HttpPost]
public async Task<ActionResult> Upload(HttpPostedFileBase file, int? id)
{
CompletedCamp completedCamp = db.CompletedCamps.Find(id);
string filename = Guid.NewGuid() + Path.GetExtension(file.FileName);
string filepath = Server.MapPath(Path.Combine("~/Surveys/", filename));
file.SaveAs(filepath);
await AzureVisionAPI.ExtractToTextFile(filepath);
ParseSurveyText parse1 = new ParseSurveyText();
await Task.Run(() => parse1.ParseTextFile(completedCamp.RollNumber, completedCamp.OfficialSchoolName, completedCamp.Date));
return View();
}

You can use client side code like jquery to register the form submit button so that as soon as form is submitted the loader appears. code would be something like:
$("form#formId").submit(function(){
$("img#loading").show();
});
Make sure to add id attribute with the id which would be used in the jquery code.
Related html should look like:
<form id="formId" class="btn btn-default" method="post"
enctype="multipart/form-data" action="#Url.Action("Upload", "CompletedCamps")">
......
......
</form><img id="loading" src="../../Content/processing.gif"
alt="Updating ..." style="display:none" />
Hope it makes sense and give you idea.

Related

How can I upload the image to server without refreshing page?

Actually I load the picture on the server. But once we do this, the page refreshes. My goal is to do this without refreshing the page. How can I do that? Is there anyone who can help?
In the code below I write onsubmit = "return false" in the form. But the picture is not uploaded to the server because the page is not refresh in this way.
VIEW
#using (Html.BeginForm("create_conference", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "registerFormValidation", onsubmit = "return false" }))
{
<div class="form-group">
<div class="input-group">
<span class="btn btn-default btn-wd btn-info btn-fill btn-file input-group-addon">
<i class="fa fa-image"></i> <input type="file" name="file" id="imgInp" accept="image/*">
</span>
<input type="text" class="form-control" readonly id="image-path" value="">
</div>
</div>
<div id="enter-room-name">
<div class="form-group">
<input type="text" placeholder="Enter Name of Room" class="form-control" required="true" id="room-name" autocomplete="false" style="text-transform:uppercase">
</div>
<button type="submit" name="add-room-submit" class="btn btn-info btn-round btn-wd">Save</button>
</div>
}
CONTROLLER
[HttpPost]
public ActionResult create_conference(HttpPostedFileBase file)
{
var path = "";
if (file != null)
{
if (file.ContentLength > 0)
{
//for checking uploaded file is image or not
if(Path.GetExtension(file.FileName).ToLower()==".jpg"
|| Path.GetExtension(file.FileName).ToLower()==".png"
|| Path.GetExtension(file.FileName).ToLower()==".gif"
|| Path.GetExtension(file.FileName).ToLower()==".jpeg")
{
path = Path.Combine(Server.MapPath("~/assets/img/conference-img"), file.FileName);
file.SaveAs(path);
ViewBag.UploadSuccess = true;
}
}
}
return View();
//return Redirect("rooms");
}
Don't read it as base64 using the fileReader or using a iframe...
Simply turn the form element into a FormData and send that to the server.
A good idea is not trying to specify method/url in the javascript keep it as general as possible and have the html markup do what it was meant to do (defining things) then you can use this function for more forms and it got a more graceful degration if javascript where turned of
function turnFormToAjax(evt) {
evt.preventDefault()
var form = evt.target
var fd = new FormData(fd)
fetch(form.target, {method: form.method, body: fd})
.then(function(res) {
// done uploading
})
}
document.querySelector('form').onsubmit = turnFormToAjax
Convert to base64 and ajax call it. Make sure the backend converts it back to an image file before saving it.
I've done it with jquery in the past.
This is the important part:
I've done it with jquery. This is the important part.
$(document).ready(function() {
$('#imageFile').change(function(evt) {
var files = evt.target.files;
var file = files[0];
if (file) {
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('preview').src = e.target.result;
};
reader.readAsDataURL(file);
// console.log(file.name)
var filename = file.name
console.log(filename);
}
});
make sure filename sends.
You can upload image using iframe, using iframe and ajax image will upload without page refresh.
You can try using my sample.
HTML:
<form id="registerFormValidation" name="registerFormValidation" action="" method="POST" enctype="multipart/form-data" >
<div id="main">
<input name="imgInp" id="imgInp" size="27" type="file" />
<input type="button" name="action" value="Upload" onclick="upload()"/>
<iframe id='my_iframe' name='my_iframe' src="">
</iframe>
</div>
</form>
This is my JS:
function upload()
{
//'my_iframe' is the name of the iframe
document.getElementById('registerFormValidation').target = 'my_iframe';
document.getElementById('registerFormValidation').submit();
}
And For Server side you can use simple Ajax method or Custom method.If you use ajax method then action will be action="javascript:submitForm();" and if you use custom method then you can use your function name.

Adding a request variable in a Django template

I am currently uploading a file to the server in Django as follows (For some unrelated reasons, I cannot use models for this form):
<div class="input-group" style="padding-top: 10px">
<div><input class="form-control" id="filename" value="Select a ZIP file to upload..." disabled></div>
<div class="input-group-btn"><input type="button" id="get_file" class="btn btn-primary" value="Browse"
style="margin-right: 3px;margin-left: 3px"></div>
<div class="input-group-btn"><input type="submit" id="upload"
class="btn btn-success" value="Upload" style="display: none"></div>
<input type="file" id="upload_file" name="upload_file" accept=".zip">
</div>
And then I some JavaScript as:
document.getElementById('get_file').onclick = function() {
document.getElementById('upload_file').click();
};
$('input[type=file]').change(function (e) {
document.getElementById('filename').value = ($(this).val());
document.getElementById('upload').style.display = "inline"
});
document.getElementById('upload').onclick = function() {
};
This works fine and I can upload the file just fine. However, now along with a file, I also want to send a string identifier. I am not sure how I can insert another request parameter on submit from this template?
The Django side looks like:
def upload(request):
"""
if request.method == 'POST' and request.FILES['upload_file']:
# Do things
So I need to add another parameter, so that I can do something like: request.GET.get('identifier') and this identifier key/value is inserted in the template code.
Does adding a hidden input inside the form work?
<input type="hidden" name="identifier" value="..."/>

how can i display a result from a server javascript function to a html page using angular

This is a form that will go to the javascript page and will upload the photo to the server
<div class="col-sm-5" style="border-right: 1px solid #ccc">
<div class="subStyle" ng-show="showDiv1">
<form id = "uploadForm"
enctype = "multipart/form-data"
action = "/api/photo"
method = "post">
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
</form>
</div>
</div>
This is the JavaScript function
function confirmUploaded() {
res.end("File was successfully uploaded -- " + outText);
}
How would i call this function from the JavaScript file to the HTML page
res.end is not a client side, It is a server side code and need to be send from the server end(NodeJS).
Make use of $http.success in angular and then on success attach the result to a particular div or header tags and use css for formatting.

How to populate a whole form after ajax GET request?

I am working on ASP.NET MVC project and have an empty form rendered by MVC controller. Right after it's been rendered, I make an AJAX GET request, and receive JSON data to populate the form.
Everything works fine when I populate each individual field (please see code below), but I have a feeling that there is a better/righter way of how to populate the entire form in one shot. Please help.
In my $.get request, I tried:
$("#content").html(data);
It simply empties my form (all fields disappear).
Then I tried:
$("#content").val(data);
Here, all fields stay blank.
Anyways, here is the code that I have (please see below).
Here is my view (.cshtml file):
#model ViewModels.ProductDetailsViewModel
<form asp-controller="ApiProduct" asp-action="Post" id="content">
<div class="form-group">
<label asp-for="Name" class="control-label">Name</label>
<input asp-for="Name" type="text" class="form-control" id="js-name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Description" class="control-label">Description</label>
<textarea asp-for="Description" rows="5" cols="40" class="form-control" id="js-description"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</form>
#section Scripts {
<script>
var id = #Model.Id;
$.get("/apiproduct/get/?id=" + id, function (data) {
$("#js-name").val(data.name);
$("#js-description").val(data.description);
});
</script>
}
​
Here is my API controller:
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var product = _repository.GetProductById(id);
return Ok(product);
}
Here is my MVC controller:
public IActionResult Details(int id)
{
var vm = new ProductDetailsViewModel()
{
Id = id;
};
return View(vm);
}
Apri478 ...Your API is giving you JSon result of your product and not html.
Above this line write console.log(data)
$("#content").html(data);
and see your response of API.
If you bind this json to form there are plenty of way.. writing custom js binding or using MVVM like angular or knockout.
try to explain more if this is not what you were expecting.

javascript form submission to modify action

I'm trying to modify the post url of a form depending on the name of the file being posted. Any suggestions very much appreciated. Here is the code (which doesn't work):
<script type="text/javascript">
function submit_form()
{
document.uploadform.action = "upload?name=" + document.uploadform.codejar.value;
return 1;
}
</script>
<form name="uploadform" method="post" onsubmit="return submit_form();">
<table>
<tr><td>Select your jar to upload</td></tr>
<tr><td> <input type="file" name="codejar" style="width: 400"></td></tr>
<tr><td><input type="submit" name="send" value="Upload jar"></td></tr>
</table>
</form>
"I'm trying to get it to do a plain http post of the file, to a url with the filename as a parameter"
Just do this then:
function submit_form() {
document.uploadform.action = document.uploadform.codejar.value;
document.uploadform.submit();
}
...and think about changing your "send" button to
<button type="button" onclick='submit_form()'>Upload jar</button>
Why would you need to do that?
You should be able to access that once the form is POSTed.
Also, browsers can send different things when getting the value from file inputs.

Categories

Resources