I'm doing a form that after the user upload the file, the checkbox will auto check, so that the user will know that their file had been uploaded.
In the form, there will have few "file upload input" and one "multiple file upload input", each of it will have a checkbox beside that will automatically checked after the file had been uploaded.
here is my code for file upload
<div><input type="checkbox" id="application" value="application" name="application"/><label for="application"><span></span></label>
</div>
<div>
<div>Application Form</div>
<div>
<input id="filename1" type="text"/>
<div class="fileUpload btn btn-primary">
<span>Add</span>
<input id="uploadBtn1" type="file" class="upload" name="browsefile" file-accept="pdf, doc, docx, jpg, jpeg, png"/>
</div>
</div>
</div>
<div><input type="checkbox" id="application2" value="application2" name="application2"/><label for="application2"><span></span></label>
</div>
<div>
<div>Application Form2</div>
<div>
<input id="filename2" type="text"/>
<div class="fileUpload btn btn-primary">
<span>Add</span>
<input id="uploadBtn2" type="file" class="upload" name="browsefile" file-accept="pdf, doc, docx, jpg, jpeg, png"/>
</div>
</div>
</div>
Script
document.getElementById('uploadBtn1').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
document.getElementById('filename1').value = filename;
}
here is the fiddle
http://fiddle.jshell.net/kpxyb74h/
here is the code for multiple file
<div><input type="checkbox" id="payment" value="payment" name="payment" /><label for="payment"><span></span></label>
</div>
<div>
<div>Payment</div>
<div>
<div id="upload_prev"></div>
<div class="fileUpload btn btn-primary">
<span>Add</span>
<input id="uploadBtn" type="file" class="upload" multiple name="browsefile" file-accept="pdf, doc, docx, jpg, jpeg, png"/>
</div>
</div>
script
$(document).on('click','.close',function(){
$(this).parents('span').remove();
})
document.getElementById('uploadBtn').onchange = uploadOnChange;
function uploadOnChange() {
var files = $('#uploadBtn')[0].files;
for (var i = 0; i < files.length; i++) {
$("#upload_prev").append('<span>'+'<div class="filenameupload">'+files[i].name+'</div>'+'<p class="close" >X</p></span>');
}
document.getElementById('filename').value = filename;
}
here is the fiddle for multiple file
http://fiddle.jshell.net/37zjr70k/
I have to separate the script because it unable to function at the same time.
$(document).ready(function () {
$("#uploadBtn1").on("change", function () {
$("#application").attr('checked','checked');
});
$("#uploadBtn2").on("change", function () {
$("#application2").attr('checked','checked');
});
});
You can do the same for multiple uploads!
Related
Hi I am trying to preview any filename when I upload to any file from local but the filename is looking like this
blob:http://localhost/cf1d307b-83ef-452b-ba7b-53af653378ce
but I want to preview file name like this logo.png or logo.jepg or logo.zip
please help me thanks.
script
function preview_images()
{
var total_file=document.getElementById("images").files.length;
for(var i=0;i<total_file;i++)
{
$('#file_preview').append("<div>"+URL.createObjectURL(event.target.files[i])+"
</div>");
}
}
HTML view
<div class="form-group mb-4">
<label >Upload ArtWork :</label>
<input type="file" class="form-control" id="images" name="images[]"
onchange="preview_images();" multiple/>
div class="row" id="file_preview"></div>
Try the following:
function preview_images()
{
const files = document.getElementById("images").files
const total_files =files.length;
const $preview = $('#file_preview')
$preview.html('')
for(var i=0; i< total_files ;i++)
{
const file = files[i]
const name = file.name
$preview.append(`<p>${name}</p>`);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group mb-4">
<label >Upload ArtWork :</label>
<input type="file" class="form-control" id="images" name="images[]" onchange="preview_images();" multiple />
<div class="row" id="file_preview"></div>
In contact form 7 when attach any file to upload there is no option to remove the attached file. How do I add a remove button or cross button beside file name?
<input type="file" name="file-637" size="40" class="wpcf7-form-control wpcf7-file" accept=".jpg,.jpeg,.png,.gif" aria-invalid="false">
<input type="file" name="file-638" size="40" class="wpcf7-form-control wpcf7-file" accept=".jpg,.jpeg,.png,.gif" aria-invalid="false">
You can use below concept with remove the attached input file
$.fn.fileUploader = function (filesToUpload) {
this.closest(".files").change(function (evt) {
for (var i = 0; i < evt.target.files.length; i++) {
filesToUpload.push(evt.target.files[i]);
};
var output = [];
for (var i = 0, f; f = evt.target.files[i]; i++) {
var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + i + "\">Remove</a>";
output.push("<li><strong>", escape(f.name), "</strong> - ",
f.size, " bytes. ", removeLink, "</li> ");
}
$(this).children(".fileList")
.append(output.join(""));
});
};
var filesToUpload = [];
$(document).on("click",".removeFile", function(e){
e.preventDefault();
var fileName = $(this).parent().children("strong").text();
// loop through the files array and check if the name of that file matches FileName
// and get the index of the match
for(i = 0; i < filesToUpload.length; ++ i){
if(filesToUpload[i].name == fileName){
//console.log("match at: " + i);
// remove the one element at the index where we get a match
filesToUpload.splice(i, 1);
}
}
//console.log(filesToUpload);
// remove the <li> element of the removed file from the page DOM
$(this).closest('div.files').find('input[type="file"]').val('')
$(this).parent().remove();
//document.getElementById("uploadCaptureInputFile").value = "";
});
$("#files1").fileUploader(filesToUpload);
$("#files2").fileUploader(filesToUpload);
$("#uploadBtn").click(function (e) {
e.preventDefault();
});
body {
padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<div class="container">
<!-- The file upload form used as target for the file upload widget -->
<form id="fileupload" action="#" method="POST" enctype="multipart/form-data">
<div class="row files" id="files1">
<h2>Files 1</h2>
<span class="btn btn-default btn-file">
Browse <input type="file" name="files1" multiple />
</span>
<br />
<ul class="fileList"></ul>
</div>
<div class="row files" id="files2">
<h2>Files 2</h2>
<span class="btn btn-default btn-file">
Browse <input type="file" name="files2" multiple />
</span>
<br />
<ul class="fileList"></ul>
</div>
</form>
</div>
//Picture upload
$(function() {
$(":file").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
};
<form id="form_roomtype" class="form-horizontal" style="padding-top: 57px;" action="roomtype" method="POST" enctype="multipart/form-data">
<input type="hidden" id="current_roomtype_id" name="current_roomtype_id" value="0">
<input type="hidden" id="roomtype_id_to_remove" name="roomtype_id_to_remove" value="0">
<input type="hidden" id="chk_tarif_applicable" name="chk_tarif_applicable" value="0">
<input type="hidden" id="photo_name" name="photo_name">
<div>
<span style="font-size: 16.85px; font-family: Arial, Helvetica, sans-serif; color: #757575;">ROOM PICTURE</span>
<br />
<br />
<input type="file" name="file" id="file" />
<br/>
<img id="myImg" src="<%=request.getContextPath()%>/images/insert_images.png" alt="room image" height="175" width="285" onclick="file" />
<br />Destination:
<input type="text" value="C:\Project\Booking_Engine\Java\booking\src\main\webapp\data" name="destination" />
</br>
<br />
<input type="submit" value="Upload" name="upload" id="upload" />
</div>
</form>
I need to take the id of the input (#file) and assign it to the hidden input with id (#photo_name) using the picture upload js on top.
I need to take the id of (<input type="file" name="file" id="file" />) and assign it to the id of (<input type="hidden" id="photo_name" name="photo_name">).
I already have the JS that I posted before... I need to use it to do the assigning of id.
I already have the id of the input file though the JS... (this.file[0]) already gives me the name of the uploaded files... now what I need is take this name and assign it to the id of the hidden input.
I need the value of photo_name in my java code below:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String currentRoomTypeIdStr = request.getParameter("current_roomtype_id");
Integer currentRoomTypeId = Integer.valueOf(currentRoomTypeIdStr);
String photoName = request.getParameter("photo_name");
if (!Objects.equals(currentRoomTypeId, null) || !Objects.equals(roomtypeIdToRemove, null)) {
try {
mUserTransaction.begin();
if (currentRoomTypeId == 0) { // Add mode
ChambreTypeEntity typeChambreEntity = new ChambreTypeEntity();
typeChambreEntity.setLibelle(inputTypeRoom);
typeChambreEntity.setCode(inputCodeRoom);
typeChambreEntity.setDescription(inputDescriptionRoom);
typeChambreEntity.setNbMinPers(inputMinPerson);
typeChambreEntity.setNbMaxPers(inputMaxPerson);
typeChambreEntity.setNbEnfGratuit(inputChild);
mEntityManager.persist(typeChambreEntity);
ChambrePhotoEntity chambrePhotoEntity = new ChambrePhotoEntity();
chambrePhotoEntity.setNomPhoto(photoName);
chambrePhotoEntity.setTypeChambre(currentRoomTypeId);
mEntityManager.persist(chambrePhotoEntity);
}
else { // Modification mode
Query query = mEntityManager.createQuery("FROM ChambreTypeEntity WHERE id=:pId")
.setParameter("pId", currentRoomTypeId);
List<ChambreTypeEntity> typeChambreEntityList = query.getResultList();
if (!typeChambreEntityList.isEmpty()) {
ChambreTypeEntity typeChambreEntity = typeChambreEntityList.get(0);
typeChambreEntity.setLibelle(inputTypeRoom);
typeChambreEntity.setCode(inputCodeRoom);
typeChambreEntity.setDescription(inputDescriptionRoom);
typeChambreEntity.setNbMinPers(inputMinPerson);
typeChambreEntity.setNbMaxPers(inputMaxPerson);
typeChambreEntity.setNbEnfGratuit(inputChild);
mEntityManager.persist(typeChambreEntity);
mEntityManager.persist(chambreTypeTarifTypeEntity);
ChambrePhotoEntity chambrePhotoEntity = new ChambrePhotoEntity();
chambrePhotoEntity.setNomPhoto(photoName);
chambrePhotoEntity.setTypeChambre(currentRoomTypeId);
mEntityManager.persist(chambrePhotoEntity);
}
}
mUserTransaction.commit();
}
But right now the value of photo_name is "". I need it to be the value that i chose while doing the picture selection.
Is the following is what you're looking for?
//Picture upload
$(function() {
// This is a better way of selecting the input field
$("input[name^=file]").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
// This is what you should do
$('#photo_name').val(this.files[0].name);
}
});
});
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form_roomtype" class="form-horizontal" style="padding-top: 57px;" action="roomtype" method="POST" enctype="multipart/form-data">
<input type="hidden" id="current_roomtype_id" name="current_roomtype_id" value="0">
<input type="hidden" id="roomtype_id_to_remove" name="roomtype_id_to_remove" value="0">
<input type="hidden" id="chk_tarif_applicable" name="chk_tarif_applicable" value="0">
<input type="hidden" id="photo_name" name="photo_name">
<div>
<span style="font-size: 16.85px; font-family: Arial, Helvetica, sans-serif; color: #757575;">ROOM PICTURE</span>
<br />
<br />
<input type="file" name="file" id="file" />
<br/>
<img id="myImg" src="<%=request.getContextPath()%>/images/insert_images.png" alt="room image" height="175" width="285" onclick="file" />
<br />Destination:
<input type="text" value="C:\Project\Booking_Engine\Java\booking\src\main\webapp\data" name="destination" />
</br>
<br />
<input type="submit" value="Upload" name="upload" id="upload" />
</div>
</form>
I have multiple inputs, I need with one button to upload all files from all the inputs (image and/or video), I found a code on web, but I can't find a way to upload or get all my files.
I am new to this procedure and unable to figure out the problem (maybe the .get() function is not right).
How to get all the files from all the inputs in one button click?..
HTML:
<div id="back" class="back">
<label id="addPicture" onclick="locatePicture(this)"
style="color:white;font-size:larger"
for="theInput">Add Image</label>
<div style="float: left">
<input id="theInput" type='file' />
</div>
<div style="float: right">
<label id="addVideo" for="uploadFileVideo" style="color:white;font-size:larger" class="AjaxList_Button">Add Video</label>
<input id="uploadFileVideo" type='file' />
</div>
</div>
<input type='Button' ID='saveAllElements' value='Done' OnClick='saveMedia()' Text='Done' />
Javascript - code found on web
function saveMedia()
{
var xhr = new XMLHttpRequest();
var data = new FormData();
var files = $(".back").get(0).files;
alert(files.length);
if (files.length == 0)
{
alert("No files");
}
else
{
for (var i = 0; i < files.length; i++)
{
data.append(files[i].name, files[i]);
}
xhr.open("POST", "UploadHandler.ashx");
xhr.send(data);
}
};
To make my weppage as compatible as possible I will go with the regular file input, the problem is that I need to offer multiple uploads.
My thought is that when the first input is set a second will be shown (up to a max of 10). Say that we have filled 5 and there is 6 visible. We now clear the second input, this will result in two empty inputs so then the last(6(empty)) input should be hidden.
Is this possible to to with Jquery?
Edit1: This is what I manage to create, it works fine. I am however sure that someone that know jquery better could make a smarter script:
In the view:
<div id="fileInput0" class="fileVisible">
<input type="file" id="file0" name="files" />
<input type="button" value="Töm" onclick="resetFileField(0)" />
</div>
<div id="fileInput1" class="fileHidden">
<input type="file" id="file1" name="files" />
<input type="button" value="Töm" onclick="resetFileField(1)" />
</div>
<div id="fileInput2" class="fileHidden">
<input type="file" id="file2" name="files" />
<input type="button" value="Töm" onclick="resetFileField(2)" />
</div>
<div id="fileInput3" class="fileHidden">
<input type="file" id="file3" name="files" />
<input type="button" value="Töm" onclick="resetFileField(3)" />
</div>
<div id="fileInput4" class="fileHidden">
<input type="file" id="file4" name="files" />
<input type="button" value="Töm" onclick="resetFileField(4)" />
</div>
<div id="fileInput5" class="fileHidden">
<input type="file" id="file5" name="files" />
<input type="button" value="Töm" onclick="resetFileField(5)" />
</div>
<div id="fileInput6" class="fileHidden">
<input type="file" id="file6" name="files" />
<input type="button" value="Töm" onclick="resetFileField(6)" />
</div>
<div id="fileInput7" class="fileHidden">
<input type="file" id="file7" name="files" />
<input type="button" value="Töm" onclick="resetFileField(7)" />
</div>
<div id="fileInput8" class="fileHidden">
<input type="file" id="file8" name="files" />
<input type="button" value="Töm" onclick="resetFileField(8)" />
</div>
<div id="fileInput9" class="fileHidden">
<input type="file" id="file9" name="files" />
<input type="button" value="Töm" onclick="resetFileField(9)" />
</div>
The Script:
function fileChangeHandler() {
var hiddenClass = 'fileHidden';
var visibleClass = 'fileVisible';
var parentDiv = $(this).parent;
var idNr = $(this).attr('id').replace('file', '');
idNr++;
if($(this).val().length > 0){
for(var i = idNr; i < 10; i++){
if($('#fileInput' + i).hasClass(visibleClass)){
if($('#file' + i).val().length < 1){ return;}
}
else{
$('#fileInput' + i).attr('class' , visibleClass);
return;
}
}
}
}
function resetFileField(id) {
var hiddenClass = 'fileHidden';
var visibleClass = 'fileVisible';
var counter;
$('#fileInput'+id).html($('#fileInput'+id).html());
$('#file'+id).change(fileChangeHandler);
for(var i = 9; i > -1 ;i--)
{
if(id != i)
{
if($('#fileInput' + i).hasClass(visibleClass)){
if($('#file' + i).val().length < 1){
$('#fileInput' + i).attr('class', hiddenClass);
}
}
}
}
}
What is a better solution?
You could have a container div which will harbor the new file input fields and a button to add new inputs:
$('#addFile').click(function() {
// when the add file button is clicked append
// a new <input type="file" name="someName" />
// to a filesContainer div
$('#filesContainer').append(
$('<input/>').attr('type', 'file').attr('name', 'someName')
);
});
Yes, you can just add a file input to the form as you would any other element:
$("#theForm").append("<input type='file' name='foo'>");
I thought this sounded familiar: [jquery]How do I add file uploads dynamically?
Another option, since you are using JQuery is the Bootstrap fileInput. It lets you upload multiple images with one control. You have additional options too like the allowed file types, size, height, width, etc.
<script type="text/javascript">
$("#postedImage").fileinput({
uploadUrl: "/SomeUrl", // you must set this for ajax uploads
maxFileCount: 10,
enctype: "multipart/form-data",
overwriteInitial: false
});
</script>
<input id="postedImage" type="file" class="file" multiple>
Here is a link for other uploaders if you are interested.
if you want to have diffrent input names
var i;
$('#addFile').click(function() {
i=i+1;
$('#filesContainer').append(
$('<input/>').attr('type', 'file').attr('name', 'file'+i)
);
});