allow file with a specific filename and extension to be uploaded - javascript

I am new to javascript and I need to check that the filename has to be uploaded only if it has the specific name and a specific extension. How do i do that? For example: I can upload file only if it has filename: can_to_do and extension: pdf else it will send out an alert asking us to change the filename

Suppose i need to upload jrxml file extension. so the validation goes something like that. say file name someFile.jrxml
var fileVal = $('#fileId').val();
if (fileVal != null && fileVal != '')
{
var ext = fileVal.split('.').pop().toLowerCase();
if ($.inArray(ext, ['jrxml']) == -1) {
jAlert('Not a valid file');
isOk = false;
}
}

I found the solution for this question I posted that is to be able to upload only if the file has a particular filename and extension. Here, for example: "ReleaseNotes.txt". It is in Javascript:
function uploadFile()
{
var fileElement = document.getElementById("fileToUpload");
var x = document.getElementById("fileToUpload");
var txt = "";
if ('files' in x) {
if (x.files.length != 0) {
for (var i = 0; i < x.files.length; i++) {
var file = x.files[i];
if ('name' in file) {
if (file.name == "ReleaseNotes.txt")
{
alert("pass");
}
else{
alert("fail");
}
}

Related

Unable to add alert notification for the image size validation and its different types format before uploading it how can we implement

code sandbox : https://codesandbox.io/s/quizzical-lamport-ql5ep
I am facing this issue. I have attached the code CodeSandbox link.
Tried to fix the issue in various methods and ways but it's not fixing. I am not able to know why it's getting an error I don't understand the exact issue in the code. Could anyone help with the solution?
Unable to add alert notification for the image size validation and its different types format before uploading it how can we implement
size <5mb and file format jpeg/png. alert notification not working
also tried this method inside it unable to upload images jpeg such as upto 2-3mb size.
const isSupported = (file) => {
let type = file?.type.split("/")[1];
let allowedTypes = ["png", "jpg", "jpeg"];
return allowedTypes.includes(type);
};
const ValidateSize = (file) => {
var FileSize = file.files[0].size / 1024 / 1024; // in MiB
const overSize = FileSize > 5;
if (overSize) {
alert("File size exceeds above 5MB");
}
return overSize;
};
const handleFileChange = (e) => {
if (ValidateSize(e.target)) {
return;
}
if (isSupported(e.target.files[0])) {
window.URL = window.URL || window.webkitURL;
const mimeType = e.target.files[0].type;
let url = window.URL.createObjectURL(e.target.files[0]);
alert("Only jpg/jpeg and png files are allowed!");
}
};
here i have a code snippet, i did the file type validation first than the file size, hope it will help
Filevalidation = () => {
//getting the file input
const fi = document.getElementById('image');
const img = fi.value.split('.').pop().toLowerCase().toString();
var imageExts = ['jpg', 'jpeg'];
// Check if any file is selected.
if (fi.files.length > 0) {
console.log(img)
if (imageExts.indexOf(img) === -1) {
alert('Only jpg/jpeg and png files are allowed!');
} if (imageExts.indexOf(img) !== -1) {
let i;
for (i = 0; i <= fi.files.length; i++) {
const fsize = fi.files.item(i).size;
const file = Math.round((fsize / 1024));
// The size of the file.
if (file >= 5120) {
alert('One or more files are bigger than 5mb');
} if (file < 5120) {
//upload file/s
}
}
}
}
}

how to specify which files should be uploaded onn file upload using javascript or jquery

I am uploading files onto a folder within my application using the code below. I would like to know how I can specify which type of files can be uploaded into that folder in my case I only want the user to be able to upload xls,xlxs and csv files. The user should not be allowed to upload docx or images etc
function OnUpload(evt) {
var files = $("#fileUpload").get(0).files;
if (files.length > 0) {
ShowUploadProgress();
if (window.FormData !== undefined) {
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
}
$.ajax({
type: "POST",
//url: "/api/ExcelBulkUpload",
url: "/api/FileUpload",
contentType: false,
processData: false,
data: data,
success: function (results) {
ShowUploadControls();
$("#uploadResults").empty();
for (i = 0; i < results.length; i++) {
$("#uploadResults").append($("<li/>").text(results[i]));
}
///"location.href='<%: Url.Action("Upload", "Controller") %>'"
window.location.href = '#Url.Action("UploadPage", "Home")';
},
error: function (xhr, ajaxOptions, thrownError) {
ShowUploadControls();
alert(xhr.responseText);
}
});
} else {
alert("Your browser doesn't support HTML5 multiple file uploads! Please use another browser.");
}
}
}
What I have researched so far
_validFileExtensions = [".xls", ".xlsx"];
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
//$('#fileinput').val('');
break;
}
You can check file extension, and based on that if file extension are allowed then call upload function, else display message that selected file not allowed to upload.
Se below example.
Note : Only client side validation is not enough, also put validation on server side.
$(document).on("change","#myfile", function (e) {
var _theFormFile = $('#myfile')[0].files[0];
var ext = getExt(_theFormFile.name);
if(ext == ".xls" || ext == ".xlxs " || ext == ".csv") {
alert('call upload file function');
} else {
alert('display false message')
return false;
}
});
function getExt(filename) {
var ext = filename.split(".");
var cnt = ext.length;
ext = ext[cnt - 1];
ext = "." + ext.toLowerCase();
return ext;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='file' name="myfile" id="myfile">
First you can select what file types the users can input by default with
<input accept=".fileType" />
And then check the filetyp if they changed the filter
function upload(){
var fileName = document.getElementById("file").files[0].name;
console.log(fileName.substr(fileName.lastIndexOf(".")));
}
<input id="file" type="file" accept=".xls,.xlxs,.csv" />
<button onClick="upload()">send</button>

How to Remove Physical Files in kendoUpload

I am using Kendo UI uploader. When I upload the files using kendoUpload, actually I rename the files using Guid.NewGuid() in server side. The problem is that, when I want to remove the files, the original file name is sent to remove handler in server side instead of guidName. How can I solve this issue?
My remove handler in server side is as follows:
[HttpPost]
public ActionResult RemoveTemp(string[] fileNames)
{
List<string> removedFiles = new List<string>();
string tempPath = Server.MapPath("~/temp/");
if (fileNames != null)
{
foreach (var fullName in fileNames)
{
File.Delete(tempPath + fullName);
removedFiles.Add(fullName);
}
}
return Json(removedFiles.ToArray());
}
My remove event in client side is as follows:
remove: function (e) {
var fileToRemove = e.files[0].name;
for (var i = 0; i < vm[item].length; i++) {
if (vm[item][i].originalName == fileToRemove) {
vm[item].splice(i, 1);
break;
}
}
// I don't know how to send guidNames here using e.data
}
You need to include the name of the saved files in the upload response, and at the client, set the name of the e.files accordingly.
Sample upload action:
[HttpPost]
public ActionResult UploadFiles()
{
// Note: We use Request.Files instead of a parameter input, to be independent of the name of the Kendo upload component
var count = Request.Files.Count;
if (count == 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var result = new List<UploadedFile>(count);
for (var i = 0; i < count; i++)
{
HttpPostedFileBase file = Request.Files[i];
if (file == null || (file.ContentLength == 0 && string.IsNullOrEmpty(file.FileName)))
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
// Some browsers send file names with full path. We are only interested in the file name.
var fileName = Path.GetFileName(file.FileName);
var tempKey = _svcUpload.SaveTempFile(file.InputStream, fileName);
result.Add(new UploadedFile
{
TempKey = tempKey,
Name = fileName,
Extension = Path.GetExtension(file.FileName),
Size = file.ContentLength
});
}
return Json(result);
}
_svcUpload.SaveTempFile() saves an uploaded file and returns its temp key (which can be the GUID of your renamed file). We include the temp key, along with other file info, in the response.
Here is the client-side upload-success handler:
function fileUploadSuccess(e) {
if (e.operation === 'upload') {
for (var i = 0; i < e.response.length; i++) {
var tempKey = e.response[i].TempKey;
e.files[i].name = tempKey;
}
}
}

How do I upload file on an aspx page without using webforms?

I have an aspx page which already has a code for uploading file using "asp:FileUpload" and webform. On a different section of page, I want to add the functionality for a user to upload file. But i do not want to use webforms or "asp:fileupload".
So, I created an HTML file that i inject as an iframe inside a div tag on the aspx.
<div id="iUploadDoc" style="height:50px;">
<iframe name='FileUpload' id='FileUpload' class='iUploadFrame' width='100%' frameborder='0' border='0'src='DocUpload.htm'></iframe></div>
I set the EnablePageMethods to true.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
And inside the HTML I made a form and with input type file.
<form method="POST" action="DocDetail.aspx.cs" id="docUpload" enctype="multipart/form-data">
<div>
<label for="fileUpload" class="inputLabel">Upload File</label>
<input type="file" id="fileUpload" name="files"/>
</div>
</form>
<div id="progUpload" style="display: none;">
<p class="uploadBox">Uploading...</p>
</div>
<span id= "selectedFile" style="display: none;"></span><span id="fileName" style="display: none;"></span>
Now, I dont know what to put in the "action" param of form.
First on the iframe, below is the script i wrote:
window.onload = load;
function uploadDocFile() {
var prog = document.getElementById("progUpload");
prog.style.cssText = 'display: block;';
var x = document.getElementById("fileUpload");
var txt = "";
var filePath = "";
var fileName = "";
if (x.value == "") {
txt += "Select a file.";
document.getElementById("selectedFile").innerHTML = txt;
} else {
filePath = x.value;
fileName = filePath.replace(/^.*[\\\/]/, '');
txt += "<br>Selected file: ";
document.getElementById("selectedFile").innerHTML = txt;
document.getElementById("fileName").innerHTML = fileName;
}
var formInfo = document.getElementById("docUpload");
document.getElementById("docUpload").style.display = "none";
window.parent.getFormData(formInfo, x ,x.value, fileName);
}
function load() {
var e = document.getElementById("fileUpload");
//var formInfo = document.getElementById("docUpload");
//fakeClick();
e.onchange = function () {
uploadDocFile();
}
}
Then on the parent page, below is the script i wrote.
DocUpload.prototype.uploadFileDoc= function (formInfo, uploadedFile, fileInfo, lastModifiedDate, name, extension, size, type) {
//blacklitsType is an array of types of file (similarly for blacklistExt) that should not be allowed to upload
if (indexOf.call(blackListType, type) < 0 && indexOf.call(blackListExt, extension) < 0) {
var idParams = { OiD: ordId, pID: pId, QID: qId }
var files = uploadedFile.files;
var fileEntries = [];
for (j = 0, len1 = files.length; j < len1; j++) {
file = files[j];
if (file.getAsEntry) {
entry = file.getAsEntry();
} else if (file.webkitGetAsEntry) {
entry = file.webkitGetAsEntry();
}
if (entry) {
isFyl = entry.isFile;
if (!isFyl) {
alert("You can not upload a folder. Uploading files (if present).");
} else {
fileItem = file.getAsFile();
fileEntries.push(fileItem);
}
} else if (!file.type && file.size % 4096 === 0) {
alert("You can not upload a folder. Uploading files (if present).");
} else {
fileEntries.push(file);
}
}
PageMethods.UploadDocument(fileEntries[0], idParams, function (res) {
if (res == true) {
alert("File uploaded successfully.");
} else {
alert("File upload failed.");
}
}, function (err) {
alert("ERROR: " + err._message);
});
} else {
window.alert('You cannot upload incorrect file types.');
}
return;
};
DocUpload.prototype.getFormData = function (formInfo, uploadedFile, fileInfo, nameInfo) {
var currDate, extension, lastModifiedDate, name, nameArr, size, type;
currDate = new Date();
lastModifiedDate = currDate;
type = '';
size = 512;
name = nameInfo;
nameArr = name.split(".");
extension = nameArr[nameArr.length - 1];
DocUpload.prototype.uploadFileDoc(formInfo, uploadedFile, fileInfo, lastModifiedDate, name, extension, size, type);
};
window.getFormData = DocUpload.prototype.getFormData;
The transfer of attributes of form from iframe to parent page work just fine. But how should i post it as file using PageMethod. Below is the page method in my code behind:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = false)]
public static bool UploadDocument(HttpPostedFileBase uploadedFile,IdParams idParams) {
bool err = false;
try{
//code
err= true;}
catch(Exception ex){err = false;}
return err;
}
No matter how much tried, either I keep getting error regarding HTTPPostedFileBase or Serialization of child not allowed.Below are only some of the errors i keep getting (not at the same time):
No parameterless constructor System.Web.HttpPostedFileBase aspx, OR
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter
What should i do?

how i to re check only image in upload

// why this code no function if me upload 1.chicken.jpg 180kb 2.chicken.pdf but chicken.pdf follow insert to database
HttpFileCollection hfc = Request.Files;
if (hfc != null)
{
string cekDir = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["docLoc"], id_hazard_report);
string PicDir;
if (Directory.Exists(cekDir)) //check Folder avlalible or not
{
PicDir = cekDir;
}
else
{
DirectoryInfo di = Directory.CreateDirectory(cekDir); // create Folder
PicDir = cekDir;
}
string fullname;
string filename;
FileUpload FileUpload1 = (FileUpload)FormView1.FindControl("FileUpload1");
string fileExt = Path.GetExtension(FileUpload1.FileName); //Get The File Extension
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength >0)
{
///full path name to check exist or not
fullname = string.Format("{0}\\{1}", PicDir, Path.GetFileName(hpf.FileName.Replace(" ", "_")));
bool ex = File.Exists(fullname);
if (hpf == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
{
if(FileUpload1.FileBytes.Length > 200000)
{
ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Tidak boleh lebih dari 200 kb');</script>");
break;
}
if (ex == true)
{
string f = Path.GetFileName(hpf.FileName.Replace(" ", "_"));
string[] a = new string[1];
a = f.Split('.');
filename = string.Format("{0}_{1}.{2}", a.GetValue(0), DateTime.Now.ToString("yymdHm"), a.GetValue(1));
}
else
{
filename = Path.GetFileName(hpf.FileName.Replace(" ", "_")).ToString();
}
///full path name to store in database with new filename
//string[] aa = new string[1];
//filename = string.Format("{0}_{1}.{2}", aa.GetValue(0), DateTime.Now.ToString("yymdHm"), aa.GetValue(1));
fullname = string.Format("{0}\\{1}", PicDir, filename);
hpf.SaveAs(fullname); //save as
InsertHazardDoc(id_hazard_report, filename);
}
else
{
FileUpload1.Focus();
ClientScript.RegisterStartupScript(Type.GetType("System.String"),"messagebox", "<script type=\"text/javascript\">alert('File Bukan Format Gambar');</script>");
break;
}
}
//}
}
}
#endregion
//Page.DataBind();
myfb._success("Hazard Report Succesfully Inserted");
}
catch (Exception ex)
{
myfb._error(ex.ToString());
}
}
// why this code no function if me upload 1.chicken.jpg 180kb 2.chicken.pdf but chicken.pdf follow insert to database
Here you define:
HttpPostedFile hpf = hfc[i];
And then you ask:
if (hpf == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
But hpf is HttpPostedFile and not a string
Change your code to:
if (fileExt == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
Additionally, you have a loop for all uploaded files.
Before that loop starts you are getting the file extension then executing the loop:
for (int i = 0; i < hfc.Count; i++)
You need to check the file extension inside of the loop:
for (int i = 0; i < hfc.Count; i++)
string fileExt = Path.GetExtension(hpf.FileName); //Get The File
Otherwise, if your first file has an allowed file extension all files in the upload will be saved.
You method to split the file name based on . is going to cause problems if the file name has a . in it such as FileName.Something.jgp. Instead use Path.GetFileNameWithoutExtension
Your timestamp to give the file a unique name can also cause issues if more than one file with the same name are uploaded at the same second. I see this issue all of the time. You might want to include milliseconds.
If you want to skip the invalid files use continue instead of break:
HttpFileCollection hfc = Request.Files;
if (hfc != null)
{
string cekDir = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["docLoc"], id_hazard_report);
string PicDir;
if (Directory.Exists(cekDir)) //check Folder avlalible or not
{
PicDir = cekDir;
}
else
{
DirectoryInfo di = Directory.CreateDirectory(cekDir); // create Folder
PicDir = cekDir;
}
string fullname;
string filename;
//FileUpload FileUpload1 = (FileUpload)FormView1.FindControl("FileUpload1");
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
///full path name to check exist or not
fullname = string.Format("{0}\\{1}", PicDir, Path.GetFileName(hpf.FileName.Replace(" ", "_")));
// get the file name here.
string fileExt = Path.GetExtension(FileUpload1.FileName); //Get The File Extension
if (FileExt == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
{
if (hpf.ContentLength.Length > 200000)
{
ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Tidak boleh lebih dari 200 kb');</script>");
continue; // break will exit the loop, use continue to go to the next file
}
if (File.Exists(fullname))
{
string f = Path.GetFileNameWithoutExtension(hpf.FileName.Replace(" ", "_"));
string timeStamp = DateTime.Now.ToString("yymdHm"); // this could fail, be more specific with your timestamp;
filename = f + timeStamp + fileExt;
// this will not work correctly if more than one "." in the file name
//string[] a = new string[1];
//a = f.Split('.');
//filename = string.Format("{0}_{1}.{2}", a.GetValue(0), DateTime.Now.ToString("yymdHm"), a.GetValue(1));
}
else
{
filename = Path.GetFileName(hpf.FileName.Replace(" ", "_")).ToString();
}
///full path name to store in database with new filename
//string[] aa = new string[1];
//filename = string.Format("{0}_{1}.{2}", aa.GetValue(0), DateTime.Now.ToString("yymdHm"), aa.GetValue(1));
fullname = string.Format("{0}\\{1}", PicDir, filename);
hpf.SaveAs(fullname); //save as
InsertHazardDoc(id_hazard_report, filename);
}
else
{
FileUpload1.Focus();
ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Bukan Format Gambar');</script>");
continue;// break will exit the loop, use continue to go to the next file
}
}
//}
}
}

Categories