How can I send a dynamically-created image from a JSP page to the action class using Javascript or jQuery-AJAX?
I need to send the image file as a file upload with Multipart/form-data.
You are allowed to make mutlipart/form-data requests with AJAX. Just gather the image binary and send it as such.
Update: based on the sample code you posted:
xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "site", true);
var formData = new FormData();
formData.append(myimg);
xmlHttp.send(formData);
Make sure you're using the API correctly. .append takes two arguments
formData.append("myimg", myimg);
Related
I am doing a chrome extension capable of getting from a webpage an image, and after I got it, I'm trying to upload it to an intranet server automatically without user iteration.
I am doing this right now.
This is on Content_script.js
...
x = $(frame1).contents().find("#image");
chrome.extension.sendRequest(x[0].src);
...
This is on background.js
chrome.extension.onRequest.addListener(function(links) {
chrome.downloads.download( { url: links ,
conflictAction: "overwrite",
filename: "get_image.jpg" },
function(DescargaId) {
var formData = new FormData();
formData.append("doc", Blob, "~/Downloads/get_image.jpg");
var request = new XMLHttpRequest();
request.open("POST", "http://192.168.0.30/app_get_pictures/upload_img.php");
request.setRequestHeader("Content-Type", "multipart/form-data");
request.send(formData);
} );
This on upload_img.php
...
$uploaddir = $_SERVER['DOCUMENT_ROOT'].'/app_get_pictures/images/';
$uploadfile = $uploaddir . basename($_FILES['doc']['name']);
move_uploaded_file($_FILES['doc']['tmp_name'], $uploadfile);
...
With this, I already download the image successfully to the local machine, but can't upload the image to the server.
It is possible to do this, or even if I can upload the image to the server directly without download it first to the local machine.
Note: I don't have any tag form on a popup page in the extension solution, and I don't have a popup page neither, because as I already said, I don't need any iteration from the user.
Thanks for your help!
Thanks to https://stackoverflow.com/users/934239/xan I resolved this problem using his advise, here is the resulting working code.
...
// With this I can download or get content image into var blob
var xhr = new XMLHttpRequest();
var kima = $(frame1).contents().find("#image");
xhr.open('GET',kima[0].src,true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = new Blob([this.response], {type: 'image/png'});
send_image(blob);
}
};
xhr.send();
....
// After the image is loaded into var blob, it can be send
// to the server side
function send_image(x){
var formData = new FormData();
formData.append("doc", x);
var request = new XMLHttpRequest();
request.open("POST", "http://192.168.0.30/app_get_image/upload_img.php");
request.send(formData);
}
All this code into the content_script of the chrome extension. Also the code of the background using API download isn't needed anymore.
Hope this could works for anybody else.
Thanks again.
Besides the fact that the callback of downloads.download does NOT indicate that the file is already downloaded (only that the download is queued)..
formData.append("doc", Blob, "~/Downloads/get_image.jpg");
What do you think this code does? Documentation, for reference.
The second parameter is supposed to hold the data of the file; the third parameter is just the file name for the purposes of naming anonymous data (e.g. in a Blob)
Instead, you pass the Blob object itself; not an instance of Blob with the data.
In fact, with this architecture, you won't be able to upload the file, since at no point does chrome.downloads API give you access to the file's contents, and you can't just access a file on a disk by filename (which is what I think you thought this code would do).
To actually access the data, you need to request it yourself with XHR (or Fetch API if you want to be "modern"). Then, you get the response object which you can request to be a Blob. Then, you can both upload the blob and invoke chrome.downloads together with createObjectURL to "download" it from your extension's memory.
I have an existing html form which uploads a file to the server as soon as the user selects an image file.
I have done something like this.
//html code
<input type="file" id="photo" name="photo" accept="image/*" />
// the usual html stuff
document.getElementById('photo').addEventListener("change",uploadImage);
function uploadImage()
{
var xhr = new XMLHttpRequest();
xhr.open("POST","/upload.php",true);
xhr.setRequestHeader("Content-type","image");
var file = document.getElementById('photo').files[0];
if(file)
{
var formdata = new FormData();
formdata.append("pic",file);
xhr.send(formdata);
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200)
{
//some code
}
};
}
But in my php file, I can't access this uploaded file. The $_POST array seems to be empty. I did a print_r for $_POST and it gave Array(). What am I doing wrong?
You are using FormData which works very much the same way a normal form does.
First of all, in PHP files will not be in $_POST but instead in $_FILES, see the documentation.
What that documentation does mention, along with the $_FILES buffer, is that you need to use the multipart/form-data encoding, any FormData transferred through an XMLHttpRequest will have this set by default, though you may want to check it if the $_FILES remain empty.
You should remove the xhr.setRequestHeader("Content-type","image"); and let the XHR object handle it, of - if that doesn't work - add
xhr.setRequestHeader("Content-type","multipart/form-data");
There is a pretty nice example right here at stackoverflow
I am using an example found here. Mozilla developers
I am interested in this example.
function upload(postUrl, fieldName, filePath)
{
var formData = new FormData();
formData.append(fieldName, new File(filePath));
var req = new XMLHttpRequest();
req.open("POST", postUrl);
req.onload = function(event) { alert(event.target.responseText); };
req.send(formData);
}
But I can't understand what goes where on this example. filePath is understandable but postUrl , fieldName I can find. I am working on image uploading on the page that has Drag and Drop zone for image uploading. How can I use this function to upload the image on my website?
Check out the FormData documentation and XMLHttpRequest documentation.
fieldName The name of the (form) field whose data is contained in value.
postUrl The URL to which to send the request.
You should have a server-side endpoint that responds to the upload request.
For example:
upload('http://mysite.com/uploader.php', 'fileField', 'path/to/my/file.jpg');
Then if you are using PHP on the server-side; you can access that field value on the server-side like this:
$my_files = $_FILES['fileField'];
On an html page I have an <object> that hosts a pdf.
I would need to access the binary data of the pdf via Javascript, but I cannot figure out how
to accomplish that. I get access to the object element itself but cannot think of a method for getting the data in it.
Is it possible at all?
You can not get the binary from an object tag, but you can make an AJAX request to the server and get it as ArrayBuffer by using the new responseType attribute:
var http = new XMLHttpRequest();
http.open("get", "somefile.pdf", true);
http.responseType = "arraybuffer";
http.onload = function(e)
{
if(http.response)
{
// http.response contains the file
}
};
http.send(null);
Note that this method only works in newer browsers and is obviously restricted by the Same-Origin-Policy.
I'm trying to find a way of letting users drag and drop individual files into an area on my page that can then get submitted along with all my other form data.
In my research I've found multiple "drag and drop" upload scripts but they all do way, way too much. I want to handle the actual uploading myself and just provide a way for users to upload files without hitting the browse button.
Is there an event in jquery (or something similar) that I should be looking for?
Any help is much appreciated!
I came across this question while researching some AJAX file upload techniques.
I created a drag and drop upload script today (its still in proof of concept stage but heres the basic steps that I took.
$('drag-target-selector').on('drop', function(event) {
//stop the browser from opening the file
event.preventDefault();
//Now we need to get the files that were dropped
//The normal method would be to use event.dataTransfer.files
//but as jquery creates its own event object you ave to access
//the browser even through originalEvent. which looks like this
var files = event.originalEvent.dataTransfer.files;
//Use FormData to send the files
var formData = new FormData();
//append the files to the formData object
//if you are using multiple attribute you would loop through
//but for this example i will skip that
formData.append('files', files[0]);
}
now you can send formData to be processed by a php script or whatever else you want to use. I didn't use jquery in my script as there a lot of issues with it it seemed easier to use regular xhr. Here is that code
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php');
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var complete = (event.loaded / event.total * 100 | 0);
//updates a <progress> tag to show upload progress
$('progress').val(complete);
}
};
xhr.send(formData);