var photo = 'http://cs323230.vk.me/u172317140/d_5828c26f.jpg';
var upload_url = 'http://cs9458.vk.com/upload.php?act=do_add&mid=62..';
var xmlhttp = getXmlHttp();
var params = 'photo=' + encodeURIComponent(photo);
xmlhttp.open("POST", upload_url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var answer2 = xmlhttp.responseText;
console.log(answer2);
alert(answer2);
}
}
};
xmlhttp.send(params);
I need to change the photo URL on the contents of the file
./DirectoryImage/imagetest.jpg
and send contents of the file
./DirectoryImage/imagetest.jpg
on upload_url.
But I don't know how send the contents of the file on upload_url in javascript...
Is it possible?
Does anyone know how make it?
Yes, you can, but it's not easy. The trick is using the FileReader object. Here's some sample code I put together for uploading an image after it's dropped into a <div>.
I'm pretty sure you can do the same with any file, as long as you can make the FileReader object from whatever your user inputs.
YourNamespace.uploadImg = function(evt) {
// Get the first file, if a stack of files has been dropped
// (to transfer the whole stack just repeat the process)
var file = evt.dataTransfer.files[0];
// Make a FileReader object
var reader = new FileReader();
// Build an AJAX request to send the file once the browser has received it.
// The FileReader will call this onload event when it's finished.
reader.onload = function(evtLoad) {
var req = new XMLHttpRequest();
req.open('POST', '/foo/bar.php', true);
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
alert("success");
}
};
// Encode the file stream properly, set the appropriate header, and send.
var params = "foo=bar&data=" + encodeURIComponent(evtLoad.target.result);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(params);
};
// This starts the whole process: read in the file as a data URL.
// When it's finished it calls the onload() that was defined above.
reader.readAsDataURL(file);
};
The MDN pages are very helpful on this whole topic, such as the FileReader object API.
Also I seem to remember browser support is poor for the usual suspects (IE6-7, etc).
It's worth mentioning that this is difficult because Javascript in browsers was not designed to talk to the server, for security purposes. Javascript is usually client-side only. File transfers and such should usually be handled with a server-side script in PHP, Perl, Ruby, etc.
Related
On a website I am automating with the help of Cefsharp I have the need to provide a javascript File.File(). The file I want to give it is locally saved and could be anything from pdfs to office documents or images. As far as CefSharp is concerned I have implemented a ISchemeHandlerFactory and ResourceHandler adding a test:// scheme and for example I have successfully added a JS file like this.
var head = document.head;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'test://local/folder/mytest.js';
head.appendChild(script);
According to the API to create a file I need
bits - An Array of ArrayBuffer, ArrayBufferView, Blob, or DOMString objects — or a mix of any such objects. This is the file content encoded as UTF-8.
So I have my scheme of test:// to give me a local file what do I need to use in javascript to get this into a file?
I worked it. I first tried a fetch but that would not let me use a custom scheme. So I had to use XMLHttpRequest
(function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var contentType = xhttp.getResponseHeader("Content-Type");
var file = new File([this.response],'3Markets.xlsx', {type: contentType,});
//use my new file etc
}
};
xhttp.open('GET', 'test://local/folder/3Markets.xlsx', true);
xhttp.responseType = "arraybuffer";
xhttp.send();
})()
The only issue or worry i have is I currently have to call
CefCommandLineArgs.Add("disable-web-security", "disable-web-security")
which i will have to have a look around how I can achieve this without disabling web security or eventually ask a question here.
This is a very general question:
I would like to download a file from the server that is only available after some input-dependent processing was done on the server via an AJAX request (e.g. using jQuery). However, I don't want to pass that file explicitly to the user as a download in the browser.
Instead, I would like to use the file for displaying some figures, which I want to create on the client-side in JavaScript because they are dynamic (specifically, can be modified by the user with sliders). As a backend, I am using Django.
Any thoughts/code on how to do this exactly, or alternatively reasons why the pipeline I imagine is not a good idea?
This code retrieves a photo as a blob from he server and then sets SRC to it when/where needed.
xmlhttp.open('GET', PHOTO_URL, true);
xmlhttp.responseType = 'blob';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var blob = xmlhttp.response;
photoImg.src = window.URL.createObjectURL(blob);
setTimeout(setOnCampusImage,0);
} else {
photoImg.src = 'unknown.png';
}
}
}
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 was using this post to help me upload files to my MVC controller. jQuery ajax upload file in asp.net mvc For some reason the controller is never getting called. I would comment on the link but I don't have enough points for stackoverflow to let me comment on stuff. My javascript code is below, besides for changing a few things to use jquery is should have the same functionality. Any ideas? If more information is needed, just comment and I'll add whatever else I can. Thanks!
Javascript:
$("#btnSubmit").click(function () {
var formdata = new FormData();
var fileInput = document.getElementById('fileInput');
formdata.append(fileInput.files[0].name, fileInput.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Index/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
return false;
});
Edit: When looking at the console output on my browser I saw the it wasn't recognizing the action(Index) that I was putting in. It would recognize the controller(Upload) but I think that is because the current view was already in the controller. Any ideas how to fix the path input for the XMLHttpRequest?
Hello I'm new at web developing so I apologize if my methods/questions makes no sense.
I am trying to load an audio file from a server directory to an audio html element. I was following fetch data example in this tutorial
var xhr = new XMLHttpRequest();
xhr.open('GET', http://*ipAddress*/audioUpload/test.mp3, true, *serverUsername*, *serverPassword*);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = new Blob([this.response], {type: 'mp3'});
var audioReader = new FileReader();
audioReader.onload = function(d) {
var e = document.createElement("audio");
e.src = d.target.result;
e.id = "audioHTMLId";
e.setAttribute("type", 'mp3');
e.setAttribute("controls", "controls");
e.setAttribute("autoplay", "true");
document.getElementById("container").appendChild(e);
}
audioReader.readAsDataURL(blob);
}
};
xhr.send();
}
However I am getting this statement in console log:
GET http://*ipAddress*/audioUpload/test.mp3 net::ERR_CONNECTION_REFUSED
And don't know why.
Also I was wondering if there were a better way to play/get audio files on client's audio html element for large mp3 files (1-1.5 hour long)?
Is this by chance in Chrome? I've send this when you try and send a request and the server disconnects. This can be HTTPS / SSL related, or a problem with the actual server . I'd check whether or not you can actually hit the file like so:
wget http://*ipAddress*/audioUpload/test.mp3
It could be that said server is actually unreachable from wherever your environment is.
As for the second half of your question, you might just want to upload the audio to youtube and embed it, rather than dealing with the hassle of dealing with it yourself (storage, bandwidth, etc). However, I'm sure someone more versed than I could give you a better answer on that.
You need to set the authorization headers manually:
....
xhr.open('GET', http://*ipAddress*/audioUpload/test.mp3, true);
xhr.setRequestHeader("Authorization", "Basic " + btoa(*serverUsername* + ":" + *serverPassword*))
....