It is common knowledge that you can use the FormData class to send a file via AJAX as follows:
var DataToSend=newFormData();
DataToSend.append(PostVariableName, VariableData); //Send a normal variable
DataToSend.append(PostFileVariableName, FileElement.files[0], PostFileName); //Send a filevar xhr=newXMLHttpRequest();
xhr.open("POST", YOUR_URL, true);
xhr.send(DataToSend);
Something that is much less known, which doesn't have any really good full-process examples online (that I could find), is sending a URL's file as the posted file.
This is doable by downloading the file as a Blob, and then directly passing that blob to the FormData. The 3rd parameter to the FormData.append should be the file name.
The following code demonstrates downloading the file. I did not worry about adding error checking.
functionDownloadFile(
FileURL, //http://...Callback, //The function to call back when the file download is complete. It receives the file Blob.ContentType) //The output Content-Type for the file. Example=image/jpeg
{
var Req=newXMLHttpRequest();
Req.responseType='arraybuffer';
Req.onload=function() {
Callback(newBlob([this.response], {type:ContentType}));
};
Req.open("GET", FileURL, true);
Req.send();
}
And the following code demonstrates submitting that file
//User VariablesvarDownloadURL="https://www.castledragmire.com/layout/PopupBG.png";
varPostURL="https://www.castledragmire.com/ProjectContent/WebScripts/Default_PHP_Variables.php";
varPostFileVariableName="MyFile";
varOutputFileName="Example.jpg";
//End of User Variables
DownloadFile(DownloadURL, function(DownloadedFileBlob) {
//Get the data to sendvar Data=newFormData();
Data.append(PostFileVariableName, DownloadedFileBlob, OutputFileName);
//Function to run on completionvarCompleteFunction=function(ReturnData) {
//Add your code in this function to handle the ajax resultvar ReturnText=(ReturnData.responseText ? ReturnData :this).responseText;
console.log(ReturnText);
}
//Normal AJAX examplevar Req=newXMLHttpRequest();
Req.onload=CompleteFunction; //You can also use "onreadystatechange", which is required for some older browsers
Req.open("POST", PostURL, true);
Req.send(Data);
//jQuery example
$.ajax({type:'POST', url:PostURL, data:Data, contentType:false, processData:false, cache:false, complete:CompleteFunction});
});
Unfortunately, due to cross site scripting (XSS) security settings, you can generally only use ajax to query URLs on the same domain. I use my Cross site scripting solutions and HTTP Forwarders for this. Stackoverflow also has a good thread about it.
To add comments, please go to the forum page for this post (guest comments are allowed for the Projects, Posts, and Updates Forums). Comments are owned by the user who posted them. We accept no responsibility for the contents of these comments.