Edit and Send back Image File User Uploads - javascript

I'm building a front-end interface for a back-end image edited process (don't know all the correct jargon).
Basically:
user should be able to upload an image file through the UI
which sends it to the server
where the image is edited in some way
then the UI should display the edited image
I'm using an XHR request with the POST method as shown below to send the image file to the server.
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
uploadButton.onclick = function() {
this.innerHTML = 'Uploading...';
//---------------
var files = fileSelect.files
var formData = new FormData();
var file = files[0]
if (file.type.match('image.*')) {
formData.append('photos[]', file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://httpbin.org/post', true);
xhr.onload = function() {
if (xhr.status === 200) {
uploadButton.innerHTML = 'Upload';
}
else {
alert('An error occurred!');
}
};
xhr.send(formData);
}; //end on-click 'Upload'
<input type="file" id="file-select" name="photos[]"/>
<button type="submit" id="upload-button">Upload</button>
My question is: In general, once the image file is sent to the server, by the code above, when/how does the edited image get sent back?
Will it be sent back as part of the server response to my POST request, and thus accessible in my processRequest callback function (assuming the server is configured to process it that way)?
Do I have to send a GET request to get the edited file?
I do not have access to the server/back-end at this point in time, and just know how the UI is supposed to work.

Related

Chrome extension xmlhttprequest() not working : succeeds to read, but fails to send information to an external server

I'm writing a chrome extension that is connected to an external php server. There are two main things that my chrome app does regarding the interaction with ther server :
1. read the stored comments from the server and show it on the extension
2. if a user writes a new comment, send it to the server so it can store the comment in the MySQL DB.
The problem I have is that while my extension has no problem fetching information from the server, it constantly fails to send new comments to the server. Since the reading function works, I assume that I have no problem with the CORS or anything.
This is the code I wrote to read the info from the server.
function getUrl() {
chrome.windows.getCurrent(function(w) {
chrome.tabs.getSelected(w.id,
function (response){
link = response.url;
//console.log(link);
hr = new XMLHttpRequest();
var info="link="+link;
//console.log(info);
hr.open("POST", "http://nardis.dothome.co.kr/nardis_core/comment_load.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onload = () => {
const data = hr.responseText;
//console.log(data);
box.innerHTML += data;
//console.log(data);
};
hr.send(info);
});
});
}
This is the code I wrote to send the information to the server.
function sendPost(){
chrome.windows.getCurrent(function(w) {
chrome.tabs.getSelected(w.id,
function (response){
//const title = document.getElementById('title').value;
const description = document.getElementById('comment').value;
link = response.url;
//console.log(link);
hr = new XMLHttpRequest();
chrome.storage.sync.get(['u_id'], function(result) {
var info="description="+description+"&link="+link+"&u_id="+result.u_id;
hr.open("POST", "https://nardis.dothome.co.kr/nardis_core/mention_create.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(info);
location.reload();
});
});
});
}

Trouble with PHP form and Ajax

I’m trying to submit a form with data to a php file without reloading the page. I also have some js code that changes the form name and values when the next btn is clicked. I had 10 questions all on 1 page and I got it to work with PHP but now I’m trying to get 1 question per page. I looked in the network tab and it looks like the xhr requests are being sent but in my database.php file I wrote $user_anwser = $_POST[‘quiz_1’]; and var dumped it and I get a NULL value. Here is the ajax code.
form.addEventListener("submit", function(e){
if (ind < 10){
e.preventDefault();
} else {
form.setAttribute("action", "results.php");
}
let data = new FormData(form);
let xhr = new XMLHttpRequest();
xhr.open('POST', '../private/database.php');
xhr.onload = function() {
if (xhr.status === 200) {
// if the response is json encoded
let response = JSON.parse(xhr.responseText); // i get a parse error there
if (response.message == 'valid') {
// redirect here
}
}
// }
xhr.send(data);
}
});

Image src not updating after setRequestHeader call

I have two AJAX functions: one for an image file upload, one for a form info upload.
File Upload
function uploadFile(insertNodeID, inputFileID){
var img = document.getElementById(inputFileID).files[0];
var form_data = new FormData();
form_data.append('file[]', img, img.name);
var objXML = new XMLHttpRequest();
objXML.onprogress = updateProgress;
objXML.onload = function() {
if(objXML.readyState==4 && objXML.status==200) {
if(objXML.responseText !== 'no'){
document.getElementById(insertNodeID).src = objXML.responseText;
}
else{
errorInOut('There was a problem uploading the file.');
}
}
};
objXML.open('POST', baseURL+'ajax/admin_fileupload/', true);
objXML.send(form_data);
Form Info Upload
function uploadFormInfo(strURL, strData, type) {
strURL = baseURL+'ajax/'+strURL+'/';
var objXML = new XMLHttpRequest();
objXML.onreadystatechange = function() {
if (objXML.readyState == 4 && objXML.status == 200) {
returnXML(objXML.responseText, type);
}
};
objXML.open("POST", strURL, true);
objXML.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
objXML.send(strData);
They both work perfect independently.
The issue I'm running into is when I call the uploadFormInfo(), then call uploadFile(), the document.getElementById(insertNodeID).src does not render the uploaded image. It still uploads the image to the server and the responseText is the correct path to the image. I did a console.log on the .src of the id AFTER the I plugged in the new image and the .src is correct BUT, it never changes in the elements tab in Chome inspect. It also works fine BEFORE I call uploadFormInfo().
I've tried and number of things (sending a separate request header for the uploadFile) and nothing works.
I'm stumped.

How to send a xmlhttp request to a php file to upload an image

I tried to make an ajax image uploader I was wondering how to send an image via a xmlHttpRequest .
Firstly i tried to send with a FormData object
var formdata = new FormData();
formdata.append('file',fileInput.files[0]);
But when I do print_r in the requested php file to _POST and _FILES but the function returned an empty array .
I tried also doing it with only the send() method but it also doesn't work where is the problem
Note : i didn't forgot the "multipart/form-data" in the setHeader.
To use the XML HTTP request features in your application, you must learn to upload files on the background with Ajax
1) Define the input elements for the file upload. Use the upload() method for the button click event to upload the file when the button is click.
<input type="file" id="uploadfile" name="uploadfile" />
<input type="button" value="upload" onclick="upload()" />
2) In the upload() method, create a FormData interface instance, and add the file element with the attached file into it. Use the send() method to send the FormData to the server.
<script>
var client = new XMLHttpRequest();
function upload()
{
var file = document.getElementById("uploadfile");
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append("upload", file.files[0]);
client.open("post", "/upload", true);
client.setRequestHeader("Content-Type", "multipart/form-data");
client.send(formData); /* Send to server */
}
/* Check the response status */
client.onreadystatechange = function()
{
if (client.readyState == 4 && client.status == 200)
{
console.log(client.statusText);
}
}
</script>

Upload file from HTML5 Filesystem by XMLHttpRequest

Trying to Upload some Images stored in Filesystem of Google Chrome.
But Im not able to upload the Image. Any Idea how to do it?
The Server receives an empty array. The Code of posttest.php is just print_r($_POST)
var xhr = new XMLHttpRequest();
xhr.open('POST', '/posttest.php', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(this.responseText);
}
};
window.resolveLocalFileSystemURL(image, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var formData = new FormData();
formData.append('image', this.result);
xhr.send(formData);
};
reader.readAsText(file);
});
});
this is the Javascript function that worked for me in chrome
function upload(filename) {
var xhr = new XMLHttpRequest();
xhr.open("post", "upload.php", true);
window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL;
filename = 'filesystem:http://localhost/temporary/' + filename;
window.resolveLocalFileSystemURL(filename, function(fileEntry) {
fileEntry.file(function(file) {
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(file);
});
});
}
Now most people on the skip the upload.php taking it for granted. But it is very important and so I paste it here:
<?php
// I had to figure out what is getting passed using var_dump($_SERVER)
$fn = (isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : false);
if ($fn) {
// AJAX call
file_put_contents(
'uploads/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}
?>
Hope this helps someone, I wasted an entire day to figure this out !
First of all, your comment isn't exactly correct, the PHP code shouldn't even be receiving a blob. It's just receiving text, because you read the file as text, while png images (and almost all image types) aren't supposed to be text, they're supposed to be binary. And Blobs themselves are perfect for storing binary data, so you don't even need to use a FileReader, you can just send the Blob itself through XMLHttpRequest!
Here is how the revised fileEntry.file callback function should look:
fileEntry.file(function(file) {
xhr.send(file);
});
It's that simple! No need to read the Blob. However, you need to do some more stuff on the
PHP side now. This code will write the contents of the uploaded image to disk, then create an <img> element that allows you to view it. Here's how the PHP /posttest.php should look for that:
<?php
$rhand=fopen('php://input','r');
$cont=fread($rhand,filesize('php://input'));
fclose($rhand);
$whand=fopen('./uploaded.png','w');
fwrite($whand,$cont);
fclose($whand);
?>
<img src="uploaded.png">
It should be pretty clear what that does if you know that php://input is where php will get input from a post request if it doesn't have a MIME type that allows it to easily put it into $_POST (For example, when you have have a request with MIME type application/x-www-form-urlencoded, PHP recognizes it and is able to parse the POST contents into $_POST, but with a Blob, it doesn't, so it just outputs it out of php://input)
Please note that none of this is tested, please put a comment if it doesn't work and I'll try to fix it!
Having encountered the same challenge myself, I was able to come up with a very sleek solution. The key is to create a new Blob, from the file object returned by the fileEntry.
window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL;
window.resolveLocalFileSystemURL(image, function (fileEntry) {
fileEntry.file(function (file) {
var formData = new FormData();
var tempBlob=new Blob([this.result], {type:this.result.type});
formData.append('image', tempBlob);
});
});

Categories

Resources