Ajax using file upload - javascript

I am creating mail page for sending mails. I need to attach some file before sending. How could I do this using AJAX? Initially I need to store those files in server and then I have to send the mail. These actions are done with in a single send button.

Check these questions:
JavaScript file uploads
How can I get Gmail-like file uploads for my web app?
What is the best multiple file JavaScript / Flash file uploader?

Look on below snippet which send text data and attached multi-files. The content-type='multipart/form-data' is set by browser automatically, the file name is added automatically too to filename FormData parameter (and can be easy read by server).
async function sendEmail() {
let formData = new FormData();
let msg = { message: emailText.value };
formData.append("email", JSON.stringify(msg));
[...attachment.files].map( (file,i) => formData.append("file"+i, file) );
try {
await fetch('your/api/upload/email', { method: "POST", body: formData });
alert("Email was send!");
} catch(e) {
alert("Problem with email sending");
}
}
<textarea id="emailText" placeholder="Type message here"></textarea><br>
<input type="file" id="attachment" multiple /><br><br>
<input type="button" value="Send email" onclick="sendEmail()" />
<br><br><span style="color:red">In this snippet API not exists so exception will be thrown but you can look on your request in:<br> chrome console> network tab</span>

I hope you know how do the normal upload. Call the upload/Reading and updating the file when click the button by using the ajax call. You have to send the local system file path as the input and then the response should contain the path in the server or error. Update the attachment link with the response in case there are no errors.

You should dynamically create a hidden iframe in your DOM and set the target of your upload form to this iframe. dont forget to set form method to POST.
you could do both uploading and message field filling in one go.
you should definitely check ready components doing this for the javascript library of your choice.

Related

Replace "C:\fakepath\" to "\\server\folder\"

I use javascript code to take the file path and paste it into the text input. I am wondering how to make it substitute a predefined server path in front of the file name instead of the path "C:\fakepath", e.g: "\server\dir\data".
$('input[type="file"]').change(function(){
$('input[type="text"]').val( $(this).val());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data">
<input type="file" onchange="this.form.filename.value = this.value">
<input type="text" name="filename">
</form>
The String object has a number of methods that you could use for this. For example using substr:
<script>
$('input[type="file"]').change(function(){
$('input[type="text"]').val( '\\server\\dir\\data'+$(this).val().substr(11));
})
</script>
Some browsers have a security feature that prevents JavaScript from knowing your file's local full path and because of which you are getting fakepath in the file path url. This security feature is added so that the server won't able to know the filesystem of your machine.
In case you you want to remove the fakepath from path then what you can do is to -
$('input[type="text"]').val( '\'+$(this).val());
This will show the the path as \file_name.extension
of what you wrote i guess that you are trying to do file upload by sending the file data from files object to the server by ajax but you cannot send this path or replace it because it's a random path generated when the server received the file to be uploaded but you can easily use FormData object to send the file to the server then you can handle it from your server
Here's an example
var photo = document.getElementById("photo")
photo.addEventListener("change",function(event) {
var form_data = new FormData();
form_data.append("file",event.target.files[0]);
$.ajax({
url: './phpScripts/up.php',
type: "post",
processData: false,
contentType: false,
data: form_data
}).done(function(e) {
//Code here
})
})
the last point if you wants to get the file path just test the event in the console console.log(event) then search for files object when you can find the file path and access it

How can we download the dynamically generate file from server?

I want download the file from server (I knew that we can't use AJAX, and serve is Servlet) and which dynamically generate according to the parameters.
Now I have the parameters in format JSON, like:
{"limitTo":"name","searchFor":["AAA","BBB","CCC"],...}
So, how can we send the request to the server with those paraleters? Do we need create some inputs?
Thanks, I found the solution which uses dojo/request/iframe, without window.open
And the code likes :
require(["dojo/request/iframe"], function(iframe){
// cancel the last request
iframe._currentDfd = null;
iframe("something.xml", {
handleAs: "xml",
data : "your json"
}).then(function(xmldoc){
// Do something with the XML document
}, function(err){
// Handle the error condition
});
// Progress events are not supported using the iframe provider
});
And then we can see download window.
Here is an article about dojo/request/iframe

Store image on server with html/javascript/mongodb

I want to upload an image from a user to the server. With the all path, it works (I can store on MongoDB). But with <input id ='image_upload' type='file' name='image_upload' />, it doesn't works (security, no full path)
So I want to know if there is an other way to do that. Maybe asolution where I store directly on the server will be ok (Using javascript, html, ajax, ... )
Thank you
You can use form data as such:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
Paticularly,
var formData = new FormData();
// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);

OrientDB - upload image via HTTP API

Hey OrientDB Community.
I'm attempting to upload an image into my DB via HTTP API. In my super basic web-page, I select a file and click upload. Simple. Once the button is clicked, I have javascript handling it with jquery and ajax.
Context: This is an educational tool which will have student profiles with their pictures. These images won't be too big (10MB - 20MB-ish).
Here is the HTML upload form:
<h2 class="heading-blue">Upload Image</h2>
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input id="upload_image" type="button" value="Upload" />
</form>
Here is the javascript code:
$('#upload_image').on('click',function(){
console.log("UPLOADING IMAGE");
var formData = new FormData($('form')[0]);
$.ajax
({
type: "POST",
url: "http://localhost:2480/uploadSingleFile/DemoPlayground",
data: formData,
??
??
success: function (){
alert('SUCCESS!');
}
});
});
I'm not sure what to use where it says "/uploadSingleFile/" in the ajax URL parameter. Also, I'm not sure what else needs to be included in the ajax call. (Hence the "??"'s up above).
Some possibilities that I've been reading about:
Call a server-side function and pass the binary data (the image) to the function for it to handle the rest. If this is a good idea, I'm not sure how to do it...so help would be appreciated.
I've read in a couple places that Orient uses Jetty to perform this action. Any pointers on that?
I've got other types of HTTP API to OrientDB requests working, but this one is troublesome and I can't figure it out on my own.
I'm open to looking at this from new angles. Please help! :) THANKS!

upload file via ajax with jquery easy ui

I'm trying to give users the possibility to import data from a file that is located on their computer by using jQuery EasyUI form widget:
<form id="my_form" method="POST">
<input type="file" name="my_file" id="my_file" />
</form>
var file_name = $('#my_file').val();
if(file_name)
{
$('#my_form').form('submit', {
url: [url_to_call],
onSubmit: function(param){
param.file_path = file_name;
}
});
}
Then when the user browse on his/her computer for the file, I wanna send the path to a jQuery ajax query to perform some upload action. The problem I have is that filename returns something like this:
C:\fakepath\[name_of_file]
Because of the fakepath string, I am not getting the real path to where the file is located on the user's computer. Does anybody know how I can fix this issue please?
Thank you
Tried this plugin http://malsup.com/jquery/form/#getting-started
this plugin provide a method called AjaxSubmit() which work fine for upload the image. I have used it in 2011.
it's have some issue in IE (old version like 6,7). You need to write some hacks. on the backend Firefox and IE upload the correct file-stream format like Data/Image but in Chrome (Webkit) you will got Octet Stream. You need to parse the file format on server to check that file is not wrong.
I have no idea what your form() function does, as no such method exists in jQuery, but the usual way of uploading a file to the server would be something like this :
$('#my_file').on('change', function() {
$.ajax({
url : [url_to_call],
data : new FormData($('#my_form').get(0)),
processData: false,
contenttype: false
}).done(function(param) {
param.file_path = file_name;
});
});

Categories

Resources