how i to re check only image in upload - javascript

// 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
}
}
//}
}
}

Related

count number entry in a CSV file using javascript in mvc

I am trying to check the file extension and count number of entry in the CSV file. At the moment the file extension check worked. My problem is the count of number row in the CSV at the moment when i run the code the count is 1 but the file selected has more than one entry. Any help please
HTML
<input type="file" name="attachmentcsv" onchange="ValidateSingleInput(this);" class="form-control" id="attachmentcsv" />
JavaScript
var _validFileExtensions = [".csv", ".CSV"];
function ValidateSingleInput(oInput) {
if (oInput.type == "file") {
var sFileName = oInput.value;
var lines = sFileName.split('\r').length;
// Check if the CSV file is valid and count the number of entry
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()) {
// show row count in the CVS file. Error is here
alert("CVS file has " + lines + " Numbers");
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry the file, " + sFileName + " selected is invalid, file extensions allowed are: " + _validFileExtensions.join(" , "));
oInput.value = "";
return false;
}
}
}
return true;
}
code below works for me
document.getElementById('attachmentcsv').addEventListener('change', readSingleFile, false);
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function (e) {
var contents = e.target.result;
var lines = contents.split("\n").length;
// Remove header count
var mobileEntryCount= lines -1
if (mobileEntryCount <= 1) {
$('#csvcount').css('display', 'block');
$('#csvcount').text('CSV File Selected has ' + mobileEntryCount + ' Mobile Number Saved');
} else {
$('#csvcount').css('display', 'block');
$('#csvcount').text('CSV File Selected has ' + mobileEntryCount + ' Mobiles Number Saved');
}
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}

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?

allow file with a specific filename and extension to be uploaded

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");
}
}

how to pass id as a parameter of FileUpload to javascript function to check extension and size of file

I am working on asp.net web application in which i have 6 FileUpload Controls
for one file upload i have created a javascript method to check file extension and file size.
but how to pass id of FileUpload upload dynamically so that only in only one method i can validate all FileUpload
my code of javacript is
var validFilesTypes = ["bmp", "gif", "png", "jpg", "jpeg", "doc", "docx", "xls", "xlsx", "htm", "html", "rar", "zip", "txt", "pdf"];
function CheckExtension() {
/*global document: false */
var file = document.getElementById("<%=txtTenderDoc.ClientID%>");
var path = file.value;
var ext = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
var isValidFile = false;
for (var i = 0; i < validFilesTypes.length; i++) {
if (ext == validFilesTypes[i]) {
isValidFile = true;
break;
}
}
if (!isValidFile) {
alert("Invalid File. Unknown Extension Of Tender Doc" + "Valid extensions are:\n\n" + validFilesTypes.join(", "));
}
return isValidFile;
}
function validateFileSize() {
/*global document: false */
var file = document.getElementById("<%=txtTenderDoc.ClientID%>");
var fileSize = file.files[0].size;
var isValidFile = false;
if (fileSize !== 0 && fileSize <= 25214400) {
isValidFile = true;
}
if (!isValidFile) {
alert("File Size Should be Greater than 0 and less than 25 mb");
}
return isValidFile;
}
and i have used this in aspx page
<asp:FileUpload ID="txtTenderDoc" onchange="var result= CheckExtension();validateFileSize(); return result"
runat="server"></asp:FileUpload>
as you can see i have to create 6 method by this to check file size and file extension how to do that in only one method....
function CheckExtension(Id) {
/*global document: false */
var file = document.getElementById(Id);
var path = file.value;
var ext = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
var isValidFile = false;
for (var i = 0; i < validFilesTypes.length; i++) {
if (ext == validFilesTypes[i]) {
isValidFile = true;
break;
}
}
if (!isValidFile) {
alert("Invalid File. Unknown Extension Of Tender Doc" + "Valid extensions are:\n\n" + validFilesTypes.join(", "));
}
return isValidFile;
}
function validateFileSize(Id) {
/*global document: false */
var file = document.getElementById(Id);
var fileSize = file.files[0].size;
var isValidFile = false;
if (fileSize !== 0 && fileSize <= 25214400) {
isValidFile = true;
}
if (!isValidFile) {
alert("File Size Should be Greater than 0 and less than 25 mb");
}
return isValidFile;
}
<asp:FileUpload ID="txtTenderDoc" onchange="var result= CheckExtension('textTenderDoc');validateFileSize('textTenderDoc'); return result" runat="server"></asp:FileUpload>
I'm assuming that your creating six different file upload controls. This way you can pass the id into the java script at compile time so you have only one method.
after searching on net finally i have solved the issue and posting it so that if anyone had similar problem this should help
// set which files are allowed in FileUpload Control
var validFilesTypes = ["bmp", "gif", "png", "jpg", "jpeg", "doc", "docx", "xls", "xlsx", "htm", "html", "rar", "zip", "txt", "pdf"];
function CheckExtension(file) {
/*global document: false */
var path = file.value;
var ext = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
var isValidFile = false;
for (var i = 0; i < validFilesTypes.length; i++) {
if (ext == validFilesTypes[i]) {
isValidFile = true;
break;
}
}
if (!isValidFile) {
alert("Invalid File. Unknown Extension Of Tender Doc" + "Valid extensions are:\n\n" + validFilesTypes.join(", "));
}
return isValidFile;
}
function validateFileSize(file) {
/*global document: false */
//getting size of the file
var fileSize = file.files[0].size;
var isValidFile = false;
if (fileSize !== 0 && fileSize <= 25214400) {
isValidFile = true;
}
if (!isValidFile) {
alert("File Size Should be Greater than 0 and less than 25 mb");
}
return isValidFile;
}
and calling these method in FileUpload Control like that
<asp:FileUpload ID="fuTenderDoc" onchange="var result=CheckExtension(this);validateFileSize(this); return result"
runat="server"></asp:FileUpload>
<asp:FileUpload ID="fuBidDoc" onchange="var result=CheckExtension(this);validateFileSize(this); return result"
runat="server"></asp:FileUpload>
<asp:FileUpload ID="fuTechnicalDoc" onchange="var result=CheckExtension(this);validateFileSize(this); return result"
runat="server"></asp:FileUpload>

Categories