Validate file exist in the AjaxFileUpload are uploaded or Pending - javascript

How can I validate that the file selected in AjaxFileUpload is already uploaded or are Pending
Here is my .aspx page code
<form id="form1" runat="server">
<asp:ToolkitScriptManager runat="server">
</asp:ToolkitScriptManager>
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
Width="400px" OnUploadComplete="OnUploadComplete" Mode="Auto" />
</form>
.aspx.cs code is
protected void OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string fileName = Path.GetFileName(e.FileName);
AjaxFileUpload1.SaveAs(Server.MapPath("~/uploads/" + fileName));
}
I had implement java script as through which I am able to validate that file exist in Ajaxfileupload or not but which file is Pending for that I am not able to validate.
function validate() {
if ($(".ajax__fileupload_fileItemInfo").length > 0) {
alert('file exist .');
}
else {
alert('select your file');
}
}
Suppose I had already uploaded 2 files and then after I add a new file to get upload but How can I validate that 2 files are uploaded and the new placed file is not uploaded.
I need to validate this from java script
I need to validate this on any button onclientclick event.

I had found the answer that worked for me
Implement the code
function validateImageUploaded() {
if ($(".ajax__fileupload_fileItemInfo").length > 0) {
if ($("div.ajax__fileupload_fileItemInfo").children('div').hasClass("pendingState"))
{
alert("found");
return false;
}
}
else {
alert('select your file');
return false;
}
}

Related

How to get the file length for an file in react js

I am using file upload in that i have added a validation if there is no file then display an error message. I am able to get the file length but when the page gets refreshed i am getting the image as well. I don't know how to get the file length from it.can anyone help me to sort this issue Thanks in advance.
Conditions i have used:
if (!values.profilePicture) {
errors.profilePicture = 'Employee Image Required';
} else if (values.profilePicture && values.profilePicture.length === 0) {
console.log('values.profilePicture.length', Object.keys(values.profilePicture).length);
errors.profilePicture = 'Employee Image Required';
}
Every file which you want to upload has file size property you can get that property onChange event.
<input type="file" accept="image/*" id="profilePic" onChange={(e)=>this.uploadImage(e)}>
and uploadImage function should be like
uploadImage=(e)=>{
let file = e.target.files[0];
if (file && !file.name) {
window.alert("Please select a file");
return false;
}
if (file.size > 10e6) {
window.alert("Please upload a file smaller than 10 MB");
return false;
}
}
Note: 10e6 is 10mb file size.

Query Regarding File Upload

I am using "File Upload" control and C# coding (backend) for uploading files(.jpeg/.png/.pdf) in my web application.
The files uploaded through this control should be saved in the server.
Everything is working fine but the problem i am facing is when a file type of xlsx or doc is been saved and the extension of that file is changed to .png or .jpeg and is being uploaded it is being uploaded into the server without any error.
While I am trying to open that image or pdf file in server it is as usually showing the error message the file cant be opened.
I have done extension validation but it does not show any effect here in this case.
Can anyone help me to get rid of this problem.(Either C# coding or Jquery Or javascript will do)
Here is how finally able to get the validation as I need using "Header codes":
System.IO.BinaryReader r = new System.IO.BinaryReader(FileUpload1.PostedFile.InputStream);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch
{
}
r.Close();
if (fileclass != "3780" || fileclass != "255216" || fileclass != "13780") /*Header codes (3780-PDF);(255216-JPG,JPEG);(13780-PNG)*/
{
/*Your code goes here(things to do with the file uploaded)*/
}
For getting values for other file formats try uploading the file and set break point and get the header code.
Can you show us how your validation looks like ?!
There is two way to check the extension of a file that you are uploading. It should be like this following :
//In your aspx file :
<asp:FileUpload ID="FileUploadControl" runat="server"/>
<asp:Button runat="server" id="Btn_Upload" text="Upload" onclick="Btn_Upload_Click" />
//In your aspx.cs file :
// First soluce
protected void Btn_Upload_Click(object sender, EventArgs e)
{
if (FileUploadControl.PostedFile.ContentType != "application/pdf")
{
//Not an PDF
}
}
// Second soluce :
protected void Btn_Upload_Click(object sender, EventArgs e)
{
string extension = Path.GetExtension(FileUploadControl.PostedFile.FileName);
if (extension != ".pdf")
{
//Not an PDF
}
}
Of course, on these code sample you can add for exception for JPEG / PNG / ...
Edit, Updated
But my problem is the extension is a proper one which i need to upload
but the file type is not i mean an excel sheet can be saved with
extension jpeg
You can use FileReader, .readAsBinaryString() to check for file headers; e.g, JFIF for .jpeg, .jpg; PNG for .png; PDF for .pdf; RegExp.prototype.test() with RegExp /JFIF|PNG|PDF/
Use accept attribute at <input type="file"> element with value set to ".jpeg,.jpg, .png,.pdf" to exclude files with extensions other than .jpeg, .jpg, .png or .pdf from being able to be selected by user at Choose File dialog.
document.querySelector("input[type=file]")
.addEventListener("change", function(e) {
console.log(e.target.files[0].type);
var reader = new FileReader();
reader.onload = function(event) {
console.log(event.target.result
, /JFIF|PNG|PDF/.test(event.target.result))
}
reader.readAsBinaryString(e.target.files[0])
})
<input type="file" accept=".jpeg,.jpg,.png,.pdf" />
There are many image format, like webp for example why not support them all?
You can convert them client side before you upload them using canvas...
function convertImage(image, mimetype, quality) {
return new Promise(function(resolve){
var canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
canvas.getContext("2d").drawImage(image, 0, 0)
canvas.toBlob(resolve, mimetype, quality)
})
}
if(input.files[0].type === 'application/pdf') {
// upload directly (not a image)
} else {
var img = new Image
img.onerror = function() { /* not an image */}
img.onload = function() {
convertImage(img, 'image/png', 1).then(function(blob){
// upload the converted image
fetch('upload', {method: 'POST', body: blob})
})
}
img.src = URL.createObjectURL(input.files[0])
}
then you use this to help filter out the accepted files you want
<input type="file" accept="application/pdf, image/*">

on buttonclick check if file exist then prompt message and revert

I have a scenario where I want to check if user adds data with same date and same region again, it should give him a prompt alert.
I tried this with code behind,like below:-
protected void btnSave_Click(object sender, EventArgs e)
{
DataTable dtExcel = new DataTable();
dtExcel.Clear();
string StrCount = String.Empty;
string connString = "";
HttpPostedFile File = FileUpload1.PostedFile;
string strFileType = Path.GetExtension(FileUpload1.FileName).ToLower();
string path = FileUpload1.PostedFile.FileName;
string Filename = path.Substring(path.LastIndexOf("\\") + 1, path.Length - path.LastIndexOf("\\") - 1);
path = Server.MapPath(#"~/Excels/" + "/" + Filename.ToString());
File.SaveAs(path);
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "SELECT * FROM [Sheet 1$]";
OleDbConnection conn = new OleDbConnection(connString);
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter daExcel = new OleDbDataAdapter(cmd);
daExcel.Fill(dtExcel);
conn.Close();
DataTable DtMain = CF.ExecuteDT("select Tran_type, Order_Date, Region_Mkey from WMS_Future_Del_Order_Hdr where Tran_type = '" + CmbTypeOfAsn.SelectedValue + "' and Order_Date = convert(datetime,'" + TxtEdate.Value + "',103) and Region_Mkey = '" + ddlRegion.SelectedValue + "'"); // checks the duplicate records here
if (DtMain.Rows.Count > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "SuccessScript", "myTestFunction()", true);
}
Also see my function for prompting the alert for duplicate message
function myTestFunction() {
if (confirm('Are you sure you want to override the file ?')) {
return true;
}
else {
return false;
}
}
but what happens here is even after cancel click, the excel file is uploaded and gets saved. I dont know why
Although Abbas Kapasi's solution based on AJAX is good one (and you do not want to/can not use the solution based on CheckBox as I suggested in my other post codebhind-javascript-alert-for-yes-and-no-not-working-exactly), if you are not familiar with AJAX or don't want to use AJAX then you may achieve it using following approach. It may seem a bit odd but you may modify it according to your requirements:
I am splitting the code to upload and find existing file/record in one procedure and the code to write/overwrite the records in another sub-procedure.
Then I am using two LinkButtons, LinkButtonLoad and LinkButtonOverwrite.
LinkButtonLoad will be attached to the call the main procedure which uploads and finds existing file/record. LinkButtonOverwrite will call the procedure to write/overwrite the records. LinkButtonOverwrite will remain hidden from the user.
In the first procedure if the system finds existing file/record it will show a client side prompt to the user to overwrite or not. If the file/record does not exist it will call second sub-procedure to write the records.
On client side, if the prompt is displayed for existing file/record and the user selects Cancel/No the process will not proceed. If the user selects OK/Yes then I'll be calling the procedure linked to the LinkButton2 to overwrite the records.
Now putting it all together:
In aspx/front end
<asp:LinkButton ID="LinkButtonLoad" runat="server" Text="Load Records" CssClass="button" ... />
<asp:LinkButton ID="LinkButtonOverwrite" runat="server" Text="ow" CssClass="button hidden" ... />
I'm using hidden CSS class to hide the button .hidden {display: none;}. Do NOT use visible="false" attribute, it'll not be available on the client side.
JavaScript on client side:
function myTestFunction() {
if (confirm('Are you sure you want to override the file ?')) {
// get the action attribute of the hidden LinkButtonOverwrite here and call it on OK
// as an alternative you may also invoke the click event of this button
var defaultAction = $('#<%=LinkButtonOverwrite.ClientID %>').prop("href");
window.location.href = defaultAction;
}
else {
return false;
}
}
LinkButtonLoad in code behind:
protected void LinkButtonLoad_Click(object sender, EventArgs e)
{
//==============================================================
// YOUR CODE TO UPLOAD THE FILE, SAVE IT SO WE MAY USE IT AGAIN
//==============================================================
if (DtMain.Rows.Count > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "SuccessScript", "myTestFunction()", true);
}
else
{
MySubToOverwrite();
}
}
LinkButtonOverwrite in code behind:
protected void LinkButtonOverwrite_Click(object sender, EventArgs e)
{
//===========================================================
// AS THE FILE IS ALREADY UPLOADED IN LINKBUTTONUPLOAD_CLICK
// YOU MAY ACCESS IT AND PERFORM REQUIRED OPERATIONS
//===========================================================
MySubToOverwrite();
}
MySubToOverwrite() code in behind:
private void MySubToOverwrite()
{
//==========================================================
// OVERWRITE YOUR RECORDS HERE
// FROM THE FILE ALREADY UPLOADED IN LINKBUTTONUPLOAD_CLICK
//==========================================================
}
Detecting duplicate records
There are a few ways you can do this. Just going to touch on the big picture here, in order of my personal preference:
Easiest method: Don't check. Prompt first. Provide a checkbox up front.
Use 2 Ajax requests: one to check for existing record, and another to save the file (if user said "OK" or if file not yet exists). Challenge: multiuser environments.
Multi-step POST back. Server code injects a dynamic control (or shows a hidden static one) that prompts user to overwrite. Ugly, but does not require JS. You may remember this from the '90s.
Versioning: more advanced, more complex, but for Enterprise systems this is the way to go. Do not overwrite files with same identifier; store a different version of it. Then you get a nice history and audit trail of who changed it. Makes it easy to go back to fix mistakes, blame people, etc.
Canceling the PostBack (if using option 3 or other postback method)
You need to bind to the correct button, and to prevent POST to the server (AKA "postback") you must return false in either
the click event handler of the rendered input type="button"
or
the submit event handler if the form
You can accomplish this by embedding the return value to myTestFunction() in the asp:Button itself:
<asp:Button ID="btnSave" runat="server" Text="Save"
OnClientClick="if(!myTestFunction()){return false;}"
OnClick="btnSave_Click" />
<script>
function myTestFunction() {
return confirm('Override the file?');
}
</script>
use ajax function with webservice to check the same data and region
Submit button code
<asp:Button ID="btnupload" runat="server" OnClientClick="javascript return checkData()"
Text="Upload" OnClick="btnupload_Click"></asp:Button>
Javacript
<script>
function checkData() {
$.ajax({
type: "POST",
url: "demo.aspx/functionName1",
data: "{parameter1:'" + param1 "',parameter2:'" + param2 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if(msg.d == 'Yes'){
if (confirm('Are you sure you want to override the file ?')) {
return true;
}
else {
return false;
}
}
else{
return true;
}
}
});
}
</script>
C# Code
using System.Web.Services; --- use this class
[WebMethod]
public static string functionName1(string parameter1, string parameter2)
{
------------------------------;
if(check Condition)
return "Yes";
else
return "No"
}
In reality, you just need the following to make it work. Use RegisterOnSubmitStatement instead of RegisterStartupScript. It would let you add script that executes in response to the button's onclick event. The script is executed before the button event is invoked, and gives you an opportunity to cancel the event.
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// You can place this in any method where you want to do the validation.
String scriptText =
"return confirm('Are you sure you want to override the file ?')";
ClientScript.RegisterOnSubmitStatement(this.GetType(),
"ConfirmSubmit", scriptText);
}
protected void btnSave_Click(object sender, EventArgs e)
{
}
Markup :
<asp:Button id="ConfirmSubmit" runat="server" OnClick="btnSave_Click"/>

Using Dropzone to upload twice with asp.net

I want to upload file by using dropzone.
First I will check this file format when user upload his/her file,
so I guess I need to set "autoProcessQueue: true" so that the uploaded file will be checked automatically.
If the file format is not right, user will be asked to upload again until upload right file.
Then when user click "save" button, this file will be uploaded into my server.
My javascript code is below:
Dropzone.options.myDropzone = {
autoProcessQueue: true,
addRemoveLinks: true,
maxFilesize: 2, // MB
acceptedFiles: ".xlsx",
maxFiles: 1,
url: 'MyPage.aspx?File=<%=Request.QueryString["File"]%>',
init: function () {
this.on("addedfile", function () {
if (this.files[1] != null) {
this.removeFile(this.files[0]);
}
});
$('#_btnTest').click(function () {
alert('aaa')
myDropzone.processQueue();
alert('bbb')
});
},
};
My aspx code
<div id="myDropzone" class="dropzone">
<div class="fallback">
<input name="file" type="file" runat="server" />
</div>
</div>
<asp:Button ID="_btnSave" runat="server" Text="Save" class="btn btn-info btn-sm" OnClick="_btnSave_Click" />
My C# code below
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["File"] != null)
{
CheckFormat();
}
}
When I upload file it will run "CheckFormat()" method and check automatically.
But my problem is that when I click "save" button will not run Page_Load() method, so I can't get the file in code-behind, this problem let me can not upload file when click "save" button.
By the way, I guess "myDropzone.processQueue();" is invalid.
what is your solution about this case?
How to do when you want to check file first then save this file to server when user click button?
Please help me and thank you so much.
When your first upload request finished, file status will become "success", in which case, this file will be skipped when you submit upload request again.
Solution:
Change file status to "queued" so it will be upload again.
Something like following:
this.on("addedfile", function (file) {
if (this.files[1] != null) {
this.removeFile(this.files[0]);
} else {
file.status = 'queued';
}
});

Javascript to pass value from server to client doesnt work

I have a fileupload control and a button in a webform.When i click on the button after selecting fileupload,it should save the image and rename it with a GUID.
protected void btnUpload_Click(object sender, EventArgs e)
{
string fileName = string.Empty;
string filePath = string.Empty;
string extension = string.Empty;
try
{
//Check if Fileupload control has file in it
if (FileUpload1.HasFile)
{
// Get selected image extension
extension = Path.GetExtension(FileUpload1.FileName).ToLower();
//Check image is of valid type or not
if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif" || extension == ".bmp")
{
//Cretae unique name for the file
fileName = Guid.NewGuid().ToString() + extension;
//Create path for the image to store
HiddenField1.Value = fileName;
filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
//Save image in folder
FileUpload1.SaveAs(filePath);
//Show the panel and load the uploaded image in image control.
//pnlCrop.Visible = true;
}
The above code works just fine,saves the image and passes the GUID to the hiddenfield.Now i want to pass the value of hiddenfield to a client side variable and then display it as an alert.
<script type="text/javascript">
function showfilename() {
setTimeout(function () {
var dpGUID = document.getElementById('<%= HiddenField1.ClientID %>').value;
alert(dpGUID);
},3000)
}
</script>
Reason for using timeout? Because i want to read value of hiddenfield after it has been assigned the value on button click.
Note:I am using two functions on Buttonclick.One on client side and other on server side as follows :
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Button" OnClientClick="showfilename()" />
Is it possible? If yes,what could be causing a problem?
Try using a RegisterClientScriptBlock
protected void btnUpload_Click(object sender, EventArgs e)
{
/*All your code here*/
//instead of HiddenField1.Value = fileName; write the line below
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "callJsFunction", "alert('" + fileName + "');", true);
}
and now you can get rid of the OnClientClick="showfilename() and the HiddenField

Categories