how to resolve a fakepath with google chrome using angular2 - google-chrome

I need to get a path from my application with angular2 typescript
the path that I get is (c:\fakepath\img.png )
I ask if there is any solution
thanks

Below is the example
ts file
upload(file)
{ console.log('file'+':'+file.value)
const inputNode = file.value.replace("C:\\fakepath\\", "");
console.log(inputNode);
}
In the above function i have passed file value as a parameter and used javascript replace function to replace "C:\fakepath\" with a blank space
html file
<input class="file" (click)="file.click()" type="file" accept="image/*" #file >
<button mat-raised-button (click)="upload(file)">Upload</button>

Related

ngf-select to Angular 8

I am migrating from Angular js to Angular 8. How can I migrate these lines of code to Angular 8:
<button class="other-button contactUsSpecific"
type="button" data-ngf-
select="contactCtrl.uploadFiles($file)"
data-ngf-max-size="9MB"
data-ngf-model-invalid="errorFiles">
<span [innerHTML]="tk.contactus.upload"></span>
</button>
I cannot find data-ngf equivalent over the internet for Angular 8.
You should have look at the answer:1 to get information on how to upload file using Angular 8.
We can add maximum size of file constraint by modifying the function call on change at file input field.
Eg:
app.component.ts
export class AppComponent {
files: FileList;
fileToUpload: File = null;
maxFileSizeBytes: number = 9e+6;
handleFileInput(event){
this.files = event.target.files;
this.fileToUpload = this.files[0];
if(this.fileToUpload.size < this.maxFileSizeBytes){
console.log("Less than required size, file will be uploaded.");
}else{
console.log("Exceeding Size");
}
}
app.component.html
<div class="form-group">
<label for="file">Choose File</label>
<input id="file" (change)="handleFileInput($event)" type="file">
</div>
Make service call in if else block. Attaching stackblitz for more clarity
Angular File Upload Demo

Function is not defined ReferecenError onchange in Angularjs

I'm having issues with onchange event for file input.
Here is my code:
Html:
<input type="file" kendo-upload k-options="uploadOptions" id="fileInput" onchange="fileUploaded(event)"/>
Angularjs code - using Typescript.
$scope.fileUploaded = (event) => {
console.log("Testing file upload");
var reader = new FileReader();
var target = event.target || event.srcElement;
reader.onload = function(e) {
$scope.$apply(function() {
$scope.readFile = reader.result;
});
};
var file = target.files[0];
reader.readAsText(file);
};
I tried to follow this and change accordingly but am still having issues.
Pass angularJS $index into onchange
I changed like this.
<input type="file" kendo-upload k-options="uploadOptions" id="fileInput" onchange="angular.element(this).scope().fileUploaded(this)">
I got this error.
Uncaught TypeError: undefined is not a function.
onchange
When I am trying to use ng-change, I have this error.
<div kendo-window="importFile" k-visible="false" k-modal="true" k-title="'Import File'"
k-min-width="450" k-max-width="450"
k-min-height="418" k-max-height="418">
<form kendo-validator="validator" ng-submit="validate($event)">
<li style="padding-bottom: 5px;">
<input type="file" kendo-upload k-options="uploadOptions" id="fileInput" ng-change="fileUploaded($event)"/>
</li>
</form>
</div>
This gives error when accessing this
$scope.importFile.center();
"TypeError: Cannot read property 'center' of undefined"
Again, works fine if I use ng-click.
Any help on this is higly appreciated.
Thanks!
You cannot use ngChange in this case since ngChange always requires ngModel and ngModel doesn't work with input type file. Also, you cannot access a function binded to $scope directly using onchange. Instead use the following:
onchange="angular.element(this).scope().fileUploaded($event)"

html code doesn't work in wordpress

this following code belongs to a wordpress custom plugin "upload". It basically creates a button to open a file browser to select one file.
<form class="file_input_uploadform" id="uploadform_2" name="uploadform_2" method="post" enctype="multipart/form-data">
<input align="center" type="button" id="input_2" value="Select File" class="file_input_button_hover">
<input type="file" accept=".$params[" pid"]="" "="" class="file_input_hidden" name="uploadedfile_2" id="upfile_2" tabindex="1" onchange="javascript: document.getElementById('fileName_2').value = this.value.replace(/c:\\fakepath\\/i, '');" onmouseout="javascript: document.getElementById('input_2').className = 'file_input_button'" onmouseover="javascript: document.getElementById('input_2').className = 'file_input_button_hover'" onclick="javascript: document.getElementById('messagelabel_2').innerHTML = ''; document.getElementById('inline_upload_message_2').style.display='none'; this.value = ''; document.getElementById('fileName_2').value = '';">
<input type="hidden" id="hiddeninput_2" name="hiddeninput_2" value="">
</form>
if we put it in a html editor, it works fine --- click on the button will pop up the file browser.
However if we put it in wordpress with
....
[upload uploadId="0"]
[upload uploadId="1"]
....
The first one doesn't work (didn't open the file browser) while the second one works(opens the file browser).
Is it any way to debug, or is it any reason why this would happen?
Search inside plugin's code for upload and you should find something like this:
add_shortcode( 'upload', 'upload_function' );
Then search for upload_function (or whatever the name of the function is). Then check what parameters the function accepts and how it works.
That way you shall find why this function doesn't accept 0 for uploadId.
More on Shortcodes: Wordpress Shortcode API

Accessing object is Google App Script

I am actually following the HtmlService documentation (https://developers.google.com/apps-script/html_service) in creating a form. I notice there is this part where it says it will be an object after user submit the form and the structure will be like this:
{ myFile: <a Blob containing the file>;
aField: <the value in the field> }
Can I know how can I access to those object in Google App Script?
In your server code:
function processForm(theForm) {
Logger.log(theForm.aField);
Logger.log(theForm.myFile.getName());
}
In your HTML:
<form id='myForm'>
<input name='myFile' type='file'>
<input name='aField'>
</form>
<script>
google.script.run.processForm(document.getElementById('myForm'));
</script>

How to allow <input type="file"> to accept only image files?

I need to upload only image file through <input type="file"> tag.
Right now, it accepts all file types. But, I want to restrict it to only specific image file extensions which include .jpg, .gif etc.
How can I achieve this functionality?
Use the accept attribute of the input tag. To accept only PNG's, JPEG's and GIF's you can use the following code:
<label>Your Image File
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
</label>
Or simply:
<label>Your Image File
<input type="file" name="myImage" accept="image/*" />
</label>
Note that this only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented, so you should always validate the uploaded file on the server also.
It should work in IE 10+, Chrome, Firefox, Safari 6+, Opera 15+, but support is very sketchy on mobiles (as of 2015) and by some reports, this may actually prevent some mobile browsers from uploading anything at all, so be sure to test your target platforms well.
For detailed browser support, see http://caniuse.com/#feat=input-file-accept
Using this:
<input type="file" accept="image/*">
works in both FF and Chrome.
Use it like this
<input type="file" accept=".png, .jpg, .jpeg" />
It worked for me
https://jsfiddle.net/ermagrawal/5u4ftp3k/
Steps:
1. Add accept attribute to input tag
2. Validate with javascript
3. Add server side validation to verify if the content is really an expected file type
For HTML and javascript:
<html>
<body>
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()"/>
<script type="text/javascript">
function validateFileType(){
var fileName = document.getElementById("fileName").value;
var idxDot = fileName.lastIndexOf(".") + 1;
var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//TO DO
}else{
alert("Only jpg/jpeg and png files are allowed!");
}
}
</script>
</body>
</html>
Explanation:
The accept attribute filters the files that will be displayed in the
file chooser popup. However, it is not a validation. It is only a
hint to the browser. The user can still change the options in the
popup.
The javascript only validates for file extension, but cannot
really verify if the select file is an actual jpg or png.
So you have to write for file content validation on server side.
This can be achieved by
<input type="file" accept="image/*" />
But this is not a good way. you have to code on the server side to check the file an image or not.
Check if image file is an actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
}
else {
echo "File is not an image.";
$uploadOk = 0;
}
}
For more reference, see here
http://www.w3schools.com/tags/att_input_accept.asp
http://www.w3schools.com/php/php_file_upload.asp
Using type="file" and accept="image/*" (or the format you want), allow the user to chose a file with specific format. But you have to re check it again in client side, because the user can select other type of files.
This works for me.
<input #imageInput accept="image/*" (change)="processFile(imageInput)" name="upload-photo" type="file" id="upload-photo" />
And then, in your javascript script
processFile(imageInput) {
if (imageInput.files[0]) {
const file: File = imageInput.files[0];
var pattern = /image-*/;
if (!file.type.match(pattern)) {
alert('Invalid format');
return;
}
// here you can do whatever you want with your image. Now you are sure that it is an image
}
}
Just as an addition: if you want to include all modern image file types with the best cross-browser support it should be:
<input type="file" accept="image/apng, image/avif, image/gif, image/jpeg, image/png, image/svg+xml, image/webp">
This allows all image file types that can be displayed in most browsers while excluding less commons formats like TIFF or formats that are not suitable for the web like PSD.
you can use accept attribute for <input type="file"> read this docs http://www.w3schools.com/tags/att_input_accept.asp
You can add specific type of image or other file type and do validation in your code :
<input style="margin-left: 10px; margin-top: 5px;" type="file" accept="image/x-png,image/jpeg,application/pdf"
(change)="handleFileInput($event,'creditRatingFile')" name="creditRatingFile" id="creditRatingFile">
handleFileInput(event) {
console.log(event);
const file = event.target.files[0];
if (file.size > 2097152) {
throw err;
} else if (
file.type !== "application/pdf" &&
file.type !== "application/wps-office.pdf" &&
file.type !== 'application/pdf' && file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== "image/png"
) {
throw err;
} else {
console.log('file valid')
}
}
In html;
<input type="file" accept="image/*">
This will accept all image formats but no other file like pdf or video.
But if you are using django, in django forms.py;
image_field = forms.ImageField(Here_are_the_parameters)
If you want to upload multiple images at once you can add multiple attribute to input.
upload multiple files: <input type="file" multiple accept='image/*'>
Simple and powerful way(dynamic accept)
place formats in array like "image/*"
var upload=document.getElementById("upload");
var array=["video/mp4","image/png"];
upload.accept=array;
upload.addEventListener("change",()=>{
console.log(upload.value)
})
<input type="file" id="upload" >
Other people's answers refactored for ReactJS (hooks)
import React from 'react';
const ImageUploader = () => {
const handleImageUpload = (e) => {
// If no file selected, return
if (e.target.files.length === 0) return false;
const file = e.target.files[0];
// If no image selected, return
if (!/^image\//.test(file.type)) {
alert(`File ${file.name} is not an image.`);
return false;
}
// ...
};
return (
<>
<input type='file' accept='image/*' onChange={(e) => handleImageUpload(e)} />
</>
);
};
export default ImageUploader;