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.
Related
We're trying to upload a song (.mp3) file from a JSP frontend written in HTML / Javascript. We need to upload to our Java backend using websockets. Does anyone have any suggestions on how we would could go about doing this?
Currently we are doing something like this on our JSP file:
<h1>Please Choose a Song file</h1>
<form name = "JSONUploadForm">
<input type = "file" name="file" accept = ".mp3"/> <br/>
<input type = "button" value = "Click to upload!" name = "button" onClick = "submitSong();"/>
</form>
Then we have our javascript function submitSong()
function submitSong(){
var songStuffs = document.getElementById("file");
console.log(songStuffs); --> we get "null" here
sendMessage(songStuffs);
alert("song sent");
}
function sendMessage(val, string) {
socket.send(string);
return false;
}
Also, here is our connect to server function. However, this functions correctly.
function connectToServer() {
socket = new
WebSocket("ws://localhost:8080/Project/socket");
socket.onopen = function(event) {
console.log("connected!");
}
You can also see our server side (.java file):
#OnMessage
public void onMessage(String message, Session session) throws IOException, EncodeException {
FileWriter fw = new FileWriter(new File(songName + ".mp3"));
fw.write(song);
BufferedReader fr = new BufferedReader(new FileReader(songName + ".mp3"));
String data = fr.readLine();
System.out.println("Song: " + data); --> Here we get "song: null"
}
Any suggestions would be greatly appreciated!
In your code you have an error
"var songStuffs = document.getElementById("file");"
Your file input without id.
this will work "var songStuffs = document.querySelector("[name=file]");"
I prefer using querySelector, because it mo flexeble and works exactly like jquery query selectors)))
You do not need any form, for upload files.
Please read this article https://www.html5rocks.com/en/tutorials/websockets/basics/,
it will be useful for you (search words "blob" at the page)
Html
<input id="file" type = "file" name="file" accept = ".mp3"/>
Code
var fileInput = document.querySelector("#file");
fileInput.addEventListener("change",function(){
connection.send(fileInput.files[0]);
});
If you need to send file and fields, you have 3 variants
create JSON {"field1":"value1","field2":"value1",
"file":"base64"}
manualy create formdata and parse form data at the
server with some webform stuff (example
https://stackoverflow.com/a/47279216/5138198)
Firstly send JSON
data, secondly send a file
Try with this, If you have to upload file you should add enctype in form.
<form enctype="multipart/form-data">
<input type = "file" name="file" id="song" accept = ".mp3"/>
</form>
Update:
You can use simply WebSocketFileTransfer plugin to send your file. This plugin helps in with many features like Auth, progress status, file/blob compatibility.
var songStuffs = document.getElementById("song").files[0];
var transfer = new WebSocketFileTransfer({
url: 'ws://ip:port/path/to/upload_web_socket_server',
file: songStuffs,
progress: function(event) {
// Update the progress bar
},
success: function(event) {
// Do something
}
});
transfer.start();
In my page I had only one html file input :
input type="file" name="file" files-model="service.file" id="filo" accept=".zip" />
And I used to get my file to be uploaded in a multi-part file request like this :
var fd = new FormData();
fd.append('file', filo.files[0]);//filo is the id of the input
//and send my http request having fd as a parameter
The problem is that now I have auto generated forms in my page with angular ng-repeat so I can no more get my file using the input ID, how can I do this now ?
Cheers,
It will be a bit tricky with javascript. this library worked for me. see example below.
<a class="btn btn-sm btn-primary"
type="file"
ngf-select="receiveSlectedFiles($file)">
Select Logo
</a>
whenever you select file, you will get it in receiveSlectedFiles($file) function. when user select valid file it will be in $file if not the $file will be null.
example in controller:
var arrayOfFiles = [];
$scope.receiveSlectedFiles = function (file) {
if (file) {
arrayOfFiles.push(file);
}
};
In service, inject Upload and then use below code to upload image:
this.uploadMultiple = function (files) {
var uri = yourApiUrl;
return Upload.upload({
url: uri,
arrayKey: '',
data: {
files: files
}
})
};
in controller, you just need to pass array of files to this service.
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/*">
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';
}
});
I'm uploading an image using AngularJS to my NodeJS server. But I have no idea how to display the image back to the user. The upload works fine, I can see the image on the server, but then how do I get it back to the client side to display it?
HTML:
<img ng-src="{{logo}}" class="col-sm-3" height="100" width="100">
<div id="dropzone" ng-file-drop="" ng-file-select="" ng-model="files" class="drop-box col-sm-9"
drag-over-class="dragover" ng-multiple="false" allow-dir="false"
accept=".jpg,.png"><b>Drop</b> image here or <b>click</b> to upload</div>
<div ng-no-file-drop>File Drag/Drop is not supported for this browser</div>
JS: (angular using ng-file-upload library)
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; ++i) {
var file = files[i];
$upload.upload({
url: "api/uploadLogo",
file: file
}).success(function (data, status, headers, config) {
console.log("file " + config.file.name + " uploaded. Response: " + JSON.stringify(data));
$scope.logo = data;
});
}
}
};
In data in success, I get things like :
Am I doing something wrong? How am I supposed to do this ?
Try handing back the location of the file and input it into a img tag like
<img ng-show="data['imgUrl']" ng-src="{{data['imgUrl']}}">
EDIT:
Searching StackOverflow came back with a similar question:
Sending an image to the server after displaying it in the UI in Angular.
Hope it helps.
EDIT 2:
Based on a better understanding of the requirements from the comments my suggestion is to use an image tag <img ng-src="data:image/png;base64,{{logo}}" /> with a $scope.image = data in the controller.
This necessitates the return of a base64 encoded image file. Which would be done in node with var base64image = new Buffer(imageFile).toString('base64'). I use node here based on the tag of node.js but any language should be able to do base64 encoding.