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';
}
});
Related
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;
}
}
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/*">
First of all, I use ng-flow (html5 file upload extension on angular.js framework)
My files are uploaded, I log the event in console.
But I don't understand where and how to save them.
Here is my html code, upload is called.
<div flow-init flow-files-submitted="$flow.upload()">
<div class="drop" flow-drop ng-class="dropClass">
<span class="btn btn-default" flow-btn>Upload File</span>
<span class="btn btn-default" flow-btn flow-directory ng-show="$flow.supportDirectory">Upload Folder</span>
<b>OR</b>
Drag And Drop your file here
</div>
Here is my config
app.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: 'upload.php',
permanentErrors: [404, 500, 501],
maxChunkRetries: 1,
chunkRetryInterval: 5000,
simultaneousUploads: 4,
singleFile: true
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}]);
upload.php is called, and $_GET is full with data,
<script>alert('alert' + array(8) {
["flowChunkNumber"]=>
string(1) "1"
["flowChunkSize"]=>
string(7) "1048576"
["flowCurrentChunkSize"]=>
string(6) "807855"
["flowTotalSize"]=>
string(6) "807855"
["flowIdentifier"]=>
string(11) "807855-3png"
["flowFilename"]=>
string(5) "3.png"
["flowRelativePath"]=>
string(5) "3.png"
["flowTotalChunks"]=>
string(1) "1"
}
)</script>
but when I'm here what I have to do to save my files?
I tried to do move_uploaded_file() on flowFilename and flowRelativePath but nothing append.
I'm new in js.
Thank you.
Look at the upload.php example script:
https://github.com/flowjs/flow.js/blob/master/samples/Backend%20on%20PHP.md
// init the destination file (format <filename.ext>.part<#chunk>
// the file is stored in a temporary directory
$temp_dir = 'temp/'.$_POST['flowIdentifier'];
$dest_file = $temp_dir.'/'.$_POST['flowFilename'].'.part'.$_POST['flowChunkNumber'];
After you upload your image with flow.js, a new post request is sent to your server. You need to handle this POST request and manipulate the file afterwards.
If you are using Java + Spring MVC it would looks like
#RequestMapping(value = "/upload",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public void handleFileUpload(#RequestParam("file") MultipartFile file) {
log.debug("REST request to handleFileUpload");
try {
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(path + file.getName())));
stream.write(file.getBytes());
stream.close();
log.debug("You successfully uploaded " + file.getName() + "!");
} catch (IOException e) {
e.printStackTrace();
}
}
I just spent half a day working with ng-flow and wanted to post the solution to this for PHP. It doesn't take advantage of the chunking and resume functionality, I just needed something that would upload without a page refresh.
First,
flow-init="{target: '/upload', testChunks:false}"
Example
<div flow-init="{target: '/upload', testChunks:false}" flow-files-submitted="$flow.upload()" flow-file-success="$file.msg = $message">
<input type="file" flow-btn />
<span flow-btn>Upload File</span>
</div>
Second,
It should now POST a request to "/upload"..... in that request exists a $_FILES array.
one line of code saved the file for me:
$result=move_uploaded_file($_FILES['file']['tmp_name'],'yourfilename');
If you are looking to control this through your angular controller, you can set the values like so:
$scope.uploader={};
$scope.upload = function (id) {
$scope.uploader.flow.opts.testChunks=false;
$scope.uploader.flow.opts.target='/upload;
$scope.uploader.flow.upload();
}
and in your html add:
<div flow-init flow-name="uploader.flow">
<button flow-btn>Add files</button>
<div>
Don
Create a folder called uploads means where you moved the temp files to here then add the code in php script.
$uploads_dir = 'uploads';
$target_file = $uploads_dir .'/'. basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
I am using dropzone.js for uploading the file in .aspx application
So Can we get Image property(Like Image height and width) after uploading file for doing some client side animation
Javascript
$(document).ready(function () {
$(".dropzone").dropzone({
url: 'BatchUpload_New.aspx',
paramName: "files", // The name that will be used to transfer the file
maxFilesize: 102, // MB
enqueueForUpload: false,
accept: function (file, done) {
return done();
}
});
});
.aspx
<div id="frmMain" runat="server" class="dropzone">
<div>
<div class="fallback">
<input name="file" type="file" multiple />
</div>
Code Behind
foreach (string s in Request.Files)
{
HttpPostedFile file = Request.Files[s];
if (file != null)
{
string fileExtension = "";
if (!string.IsNullOrEmpty(file.FileName))
{
fileExtension = Path.GetExtension(file.FileName);
}
// IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory
string savedFileName = Path.Combine(#"C:\Temp\", Guid.NewGuid()+ fileExtension);
file.SaveAs(savedFileName);
lbTtest.Text += " " + file.FileName;
}
Dropzone adds data to the file object you can use when events fire. You can access file.width and file.height if it's an image, as well as file.upload which is an object containing: progress (0-100), total (the total bytes) and bytesSent.
For now I am able to upload the file successfully... What I'm trying to do right now is show an alert box if the file was successfully uploaded or show an alert for the error/exception if not...
Here is my view:
using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { #id = "File", enctype = "multipart/form-data"}))
{
<div class="control-group">
<input type="file" id="file" name="file" />
<input type="submit" value="Upload" />
</div>
}
Here is my controller:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
try
{
//some code here for the upload....
/*In this part is my problem...Both Lines below is not showing the alert...*/
//return new JavaScriptResult() { Script = "alert('The calendar XML file was uploaded successfully!');" };
//return JavaScript("alert('The calendar XML file was uploaded successfully!');");
}
catch (Exception e)
{
log.Error("HomeController::Upload()", e);
return new JavaScriptResult() { Script = "alert(\"" + e.Message + "\");" };
}
}
What i would like is that my view would still remain... no redirection of page... just merely showing of that alert box for the message...Thank you! Any ideas is greatly appreciated coz i know this way of mine is not recommended... :)
This is what i've done to get the Alert from the controller
Here is the View Code:
#using (#Html.BeginForm("DoSomething","secure"))
{
<input type="submit" value="get alert" />
}
Here is Controller Code:
[HttpPost]
public ActionResult DoSomething()
{
string message = "hai";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
//return Content("<script type='text/javascript'>alert('Hello there');</script>"); //You can get the alert with this line also
return Content(sb.ToString(), "text/javascript");
}
Even there is no need of script, it directly shows alert when the get alert button is clicked
Hope it helps
I was able to find the right solution here.
The link above was for showing a confirmation box before submitting the form and showing an alert for the message that was a json object returned by my controller...
return Json(new { isok = true, message = "Successfully uploaded the calendar XML file!" }, "application/octet-stream");