I'm creating a asynchronous upload element with the javascript code bellow:
$("#file-input").change(function(){
uploadImage(this.files[0]);
});
function uploadImage(imageFileHTMLInput) {
var xml = new XMLHttpRequest();
var data = new FormData();
data.append('file', cover);
xml.open('POST', url);
xml.send(data);
xml.onreadystatechange = function() {
if(xml.readyState === 4) {
if(xml.status === 200) {
var response = JSON.parse(xml.responseText);
// handle response
} else {
var error = JSON.parse(xml.responseText);
// handle error
}
}
};
}
How can I handle this post in a Symfony2 server? I need to save this file in the server and return the image url.
UPDATED:
I made some changes on my code to works fine. I have change all way to do the upload.
You will get the data from your POST request in the controller via
$request->files->get('your_file_identifier_name');
Server side, you'll get an instance of File
Related
So, I have a JS script that sends a request to the server and that works fine. However, I want the frontend to recieve a response containing some information and read it on the frontend and execute a function.
uploadButton.addEventListener("click", () => {
var formData = new FormData();
var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
if (request.response.result == "Success") {
console.log("Result is success")
window.location = request.response.url;
}
}
My controller looks like this.
[HttpPost("/page/upload")]
public IActionResult Upload()
{
*working parts pertaining to reading the request are omitted*
var redirectUrl = Request.Host + "/" + page.PageURL;
return Json(new { result = "Success", url = redirectUrl});
}
What I want is for my JS script to access the returned Json and its contents. How would I do this?
Try using the following code. It will subscribe the readystatechange event and run when API response has been received
uploadButton.addEventListener("click", () => {
var formData = new FormData();
var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
request.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
var responseData = JSON.parse(this.responseText);
if (responseData.result == "Success") {
console.log("Result is success")
window.location = responseData.url;
}
}
});
});
I've got a problem in my ASP.net Core application. I use MVC. I send a file from js to controller using:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Test/Sing", true);
xhr.send(fd);
then I got it in controller action:
[HttpPost]
public IActionResult Sing()
{
var file = Request.Form.Files[0];
byte[] filedata = null;
using (var target = new MemoryStream())
{
file.CopyTo(target);
filedata = target.ToArray();
}
\\some filedata processing
return RedirectToAction("Question");
}
The filedata is something that I need to process and then redirect to another action. When I put a breakpoint at the end of using (MemoryStream) I can see that the filedata is filled with data I need but when I want to redirect to action nothing happens. It looks like a process with the xmlhttprequest is still running on the client side and waiting for response. Am I right? How to get the file, cut the process, perform some file processing and be able to redirect to another action?
You should manually handle the redirect using window.location.href in success callback function of ajax/XMLHttpRequest .
If using XMLHttpRequest ,you can add listener for load events ,the listener must be added before the send() function:
function reqListener () {
window.location.href = "url";
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
If using AJAX redirect in success callback function :
success: function (response) {
window.location.href = "url";
}
Controller :
return Json("ok");
//Or return the url
return Json(new { redirectToUrl = Url.Action("action", "contoller") });
I've read the readme file at https://github.com/cloudinary/cloudinary_tinymce but still can't understand how to do it. Plus they do it on Ruby on Rails, which doesn't really help.
Do I really need to do server-side endpoint? It only asks for a signed URL. But I don't need it to be signed. How do I do it within JavaScript and HTML alone? I don't want to do anything inside my server except to render templates.
edit: I tried it with image_upload handler and it uploads to my Cloudinary account. But it won't give me the url for the image on successful upload (I expect to get something like https://res.cloudinary.com/strova/image/upload/v1527068409/asl_gjpmhn.jpg). Here's my code:
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'https://api.cloudinary.com/v1_1/strova/upload');
xhr.onload = function () {
var json;
if (xhr.status !== 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
formData.append('upload_preset', cloudinary_upload_preset);
xhr.send(formData);
}
Try "faking" a POST request for one. I am still trying. To figure out why the documentation "requires" a POST request. The PHP example: https://www.tinymce.com/docs-3x//TinyMCE3x#Installation/ just echos back what gets POSTED to server. The plugin must be interpolated the posted content.
Inspired by your code, I was able to resolve this pain point for myself. The missing part was that after parsing the response, the secure_url from the response needed to be called and assigned to json in the format required by TinyMCE. Following is the code:
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
//restricted it to image only using resource_type = image in url, you can set it to auto for all types
xhr.open('POST', 'https://api.cloudinary.com/v1_1/<yourcloudname>/image/upload');
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var url = response.secure_url; //get the url
var json = {location: url}; //set it in the format tinyMCE wants it
success(json.location);
}
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
formData.append('upload_preset', '<YourUnsignedUploadPreset>');
xhr.send(formData);
}
I have local image URL and I want to get the blob from it.
The only way I found was to do HTTP request 'get' on the local URL, and read the returned blob... but this is such a strange way.
The code snippet using HTTP:
function readBody(xhr) {
var data;
if (!xhr.responseType || xhr.responseType === "text") {
data = xhr.responseText;
} else if (xhr.responseType === "document") {
data = xhr.responseXML;
} else {
data = xhr.response;
}
return data;
}
var xhr=new XMLHttpRequest();
xhr.open('GET',results[i],true);
xhr.responseType='blob';
xhr.send();
xhr.onreadystatechange=function()
{
var blob;
if(xhr.readyState==4)
{
blob=readBody(xhr);
uploadPhoto(blob,storageRef);
}
};
Your image needs to be converted to base64 and then from base64 in to binary. This is done using .toDataURL() and dataURItoBlob()
It's pretty fiddly process, I've created a tutorial you can follow which walks you through the process.
Hey guys I am using a executePostHttpRequest function that looks exactly like the code posted below. Currently when I run the function I get a server response with the appropriate data but I am not sure how I can work with the response data? how do I store it in to a variable to work with?
Javascript executePostHttpRequest
function executePostHttpRequest(url, toSend, async) {
console.log("====== POST request content ======");
console.log(toSend);
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", url, async);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.setRequestHeader("Content-length", toSend.length);
xmlhttp.send(toSend);
console.log("====== Sent POST request ======");
}
Here is what I am doing to execute it. Using Javascript
var searchCriteria = JSON.stringify({
displayName : search_term
});
console.log("Search: "+searchCriteria) //Search: {"name":"John, Doe"}
var response = executePostHttpRequest("/web/search", searchCriteria, true);
console.log(response) //undefined
So currently the console.log for response shows undefined. But if I take a look at the network tab on Chrome Dev Tools and look at the /web/search call I see a JSON string that came back that looks something like this.
[{"id":"1","email":"john.doe#dm.com","name":"John, Doe"}]
I'd like to be able to display the data from this response to a HTML page by doing something like this.
$("#id").html(response.id);
$("#name").html(response.name);
$("#email").html(response.email);
I tried taking another route and using Jquery POST instead by doing something like this.
var searchCriteria = JSON.stringify({
displayName : search_term
});
console.log("Search: "+searchCriteria) //Search: {"name":"John, Doe"}
$.post("/web/search", {
sendValue : searchCriteria
}, function(data) {
$.each(data, function(i, d) {
console.log(d.name);
});
}, 'json').error(function() {
alert("There was an error searching users! Please contact administrator.");
});
But for some reason when this runs I get the "There was an error" with no response from the server.
Could someone assist me with this? Thank you for taking your time to read it.
Your executePostHttpRequest function doesn't do anything with the data it's receiving. You would have to add an event listener to the XMLHttpRequest to get it:
function getPostData(url, toSend, async, method) {
// Create new request
var xhr = new XMLHttpRequest()
// Set parameters
xhr.open('POST', url, async)
// Add event listener
xhr.onreadystatechange = function () {
// Check if finished
if (xhr.readyState == 4 && xhr.status == 200) {
// Do something with data
method(xhr.responseText);
}
}
}
I've added the method parameter for you to add a function as parameter.
Here's an example of what you were trying to do:
function displayStuff(jsonString) {
// Parse JSON string
var data = JSON.parse(jsonString)
// Loop over data
for (var i = 0; i < data.length; i++) {
// Get element
var element = data[i]
// Do something with its attributes
console.log(element.id)
console.log(element.name)
}
}
getPostData('/web/search', searchCriteria, true, displayStuff)