In the web, I'm building local file drag and drop upload to the server with the ruby on rails, dragging and drop a file working fine, but how to get the dragged file content in the controller with the drop event? I'm getting the file with event.datatransfer, send file through Javascript with XMLHttpRequest.
function handleDrop(event)
{
preventDef(event)
var dt = event.dataTransfer;
var files = dt.files;
for(var i = 0; i < files.length;i++)
{
http_request = new XMLHttpRequest();
var boundaryString = 'the_boundery--';
var boundary = '--' + boundaryString;
var requestbody = boundary + '\n'
+ 'Content-Disposition: form-data; name="thefilename"' + '\n'
+ '\n'
+ files[i].fileName + '\n'
+ '\n'
+ boundary + '\n'
+ 'Content-Disposition: form-data; name="thefile"; filename="'
+ files[i].fileName + '"' + '\n'
+ 'Content-Type: application/octet-stream' + '\n'
+ '\n'+files[i].path
+'\n'+ files[i].getAsBinary()
+ '\n'
+ boundary;
var preview = document.getElementById("preview");
preview.src = files[i].getAsDataURL();
var queryString="";
queryString="filename="+files[i].fileName+'&'+"file_to_upload=="+files[i].getAsBinary();
var actionUrl="/shortening/dr";
http_request.open('POST',actionUrl,true);
http_request.setRequestHeader("Content-type", "multipart/form-data; \
boundary=\"" + boundaryString + "\"");
http_request.setRequestHeader("Connection", "close");
http_request.setRequestHeader("Content-length", requestbody.length);
http_request.sendAsBinary(requestbody);
}
}
using this script calling the url and send the file through sendAsBinary method
Post method not calling the controller with the respective action
How to get the requestbody in the controller ?
Any idea?
First off, use some kind of javascript library to do AJAX and pretty much everything else. I'd suggest jQuery (http://jquery.com/)
Unfortunatelly no browser supports file uploads through XmlHttpRequest.
Read sometime ago something about Firefox supporting it, but that would be restricting and I'm not even sure that really works.
You could make an iframe and with the drop event, set the file field inside the iframe and then submit the iframe.
Related
I am new to JavaScript. I am working with a website. In this website i have provide a functionality to the users to download a file. Now i need to know is there any way to send those downloaded file to email. My code for downloading content is given below.
function download2(data, filename, type) {
var file = new Blob([data], { type: type });
if (window.navigator.msSaveOrOpenBlob)
window.navigator.msSaveOrOpenBlob(file, filename);
else {
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
};
and my send mail function is given below:
function sendMail(mail, name, roll, cls, sec, grp) {
var link = "mailto:" + mail
+ "?cc=ictpracticalslc#gmail.com"
+ "&subject=" + escape("AnswerSheet Submitted By " + name + " Class " + cls + " Section " + sec + " Group " + grp)
+ "&body=" + escape("My Roll Is " + roll)
;
window.location.href = link;
};
when i call download2("<p>Hello</p>", "hello.html", "text/plain"). A file named hello.html is downloaded in my local machine. But i need to attach this file in sendMail function. so that users can send email with this attachment.
I need to update the sendMail function so that it can accept an attachment which is downloaded by download2 function.
I am badly need this functionality. I am stuck here for 15 days and find no suitable solution. I need to do this with only javascript or jquery.
I have a function in my Apache Cordova application to create a new list item inside a sharepoint list, and I was wondering if it was possible to add an image to this new item, this would come as an 'attachment' in the sharepoint list. My function to add a new item looks like this:
function CreateItem(Title, Description) {
var soapEnv =
"<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soapenv:Body>" +
"<UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">" +
"<listName>LISTNAME</listName>" +
"<updates>" +
"<Batch OnError=\"Continue\">" +
"<Method ID=\"1\" Cmd=\"New\">" +
"<Field Name=\"ID\">New</Field>" +
"<Field Name=\"Title\">" + Title + "</Field>" +
"<Field Name=\"Description\">" + Description + "</Field>" +
"</Method>" +
"</Batch>" +
"</updates>" +
"</UpdateListItems>" +
"</soapenv:Body>" +
"</soapenv:Envelope>";
$.ajax({
url: "URL",
type: "POST",
dataType: "xml",
data: soapEnv,
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction",
"http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
},
complete: processCreateResultSuccess,
contentType: "text/xml; charset=\"utf-8\"",
error: processCreateResultError
});
}
The image is taken with the Cordova app and has the ID "image". Any thoughts?
SharePoint: AddAttachment SOAP Web Service
Yes, you can use SharePoint SOAP web services to upload an image attachment to a list. However, there are some limitations.
My demo below uses the AddAttachment action of the Lists web service. The required parameters are listed and can be modified for your own environment. The demo simply adds a text file attachment, but it works with images and other file types too. Also works with SP 2007-2013.
The limitation is that files must be encoded as base-64 for transfer within the SOAP envelope. On the client side, base-64 file encoding is not a trivial task. I've done it using the FileReader object, but that is only available in modern browsers (IE10). There might be other options with mobile devices, but I've not researched it. Alternatively, you might look at the newer REST API.
<html>
<body>
<script type='text/javascript'>
function addAttachment( ) {
var webUrl = '', // base url when list in sub site
listName = 'CustomList', // list name or guid
listItemID = '1', // list item id
fileName = 'HelloWorld.txt', // file name
attachment = 'SGVsbG8gV29ybGQ=', // base-64 encode file data "Hello Word!"
xhr, soap;
soap = (
'<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope '+
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '+
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" '+
'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
'<soap:Body>'+
'<AddAttachment xmlns="http://schemas.microsoft.com/sharepoint/soap/">'+
'<listName>' + listName + '</listName>'+
'<listItemID>' + listItemID + '</listItemID>'+
'<fileName>' + fileName + '</fileName>'+
'<attachment>' + attachment + '</attachment>'+
'</AddAttachment>'+
'</soap:Body>'+
'</soap:Envelope>'
);
xhr = new XMLHttpRequest();
xhr.open( 'POST', webUrl + '/_vti_bin/Lists.asmx', true );
xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xhr.setRequestHeader('SOAPAction', 'http://schemas.microsoft.com/sharepoint/soap/AddAttachment');
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
// do something - returns file path or error message
console.info( xhr.status + '\n' + xhr.responseText );
}
xhr.send( soap );
}
</script>
</body>
</html>
I need the complete code for uploading a file in dojo.
Especially the ajax call and its button creation, and its url must get stored into database. I use the following code, but it's not working:
function uploadPicture()
{
alert("yes");
var xhrArgs = {
url:"/service/ajax/uploadPictureToOption/",
form: dojo.byId("optionsForm"),
handleAs: "json",
content :{},
load: function(response, ioArgs){
if (response == "failed")
{
alert("Failed");
window.location.reload();
}
else if (response == "success")
{
window.location.reload();
}
else
{
alert("Successfully deleted");
window.location.reload();
}
},
}
var deferred = dojo.xhrPost(xhrArgs);
}
Making assumption that your file is binary, otherwise see Moz MDN - File.getAsBinary
Optionally you could make use of FormData (xhr2).
IFrame is the way to go since IE doesnt support HTML5 up until IE10
var xhr=(window.XMLHttpRequest && new window.XMLHttpRequest()),
input = dojo.byId('inputelementId')
boundary = "---------------------------" + (new Date).getTime(),
message = ""
xhr.open("POST", this.getUrl());
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
// if(input.files.length > 1) {
message += "--" + boundary + "\r\n"
+ 'Content-Disposition: form-data; name="' + input.name + '";'
+ ' filename="'+ (input.files ? input.files[0].name : input.value) + '"' + EOL;
message += "Content-Type: application/octet-stream" + "\r\n" + "\r\n";
// }
if(!!xhr.sendAsBinary) {
xhr.send(message + input.files[0].getAsBinary())
} else {
// here is the kicker; IE does not support neither FileData nor AsBinary
var fobj = new ActiveXObject("Scripting.FileSystemObject"),
fd = fobj.OpenTextFile(input.value, 1);
xhr.send(message + fd.ReadAll());
fd.Close();
}
to begin with your idea for a file upload is currently imposible using the xhr modules of dojo (AKA AJAX[only handdles plain text]).
The closest posible thing you can do is to subbmit the form to a hidden iframe.
EDIT
The code for a hidden iframe should be something like this:
<form method=”post” action=”formProcess.php” target=”hiddenIFrame”>
<input type=”file” name=”test” />
<input type="submit" value="Submit">
</form>
<iframe style=”width:0px;height:0px;border:0px;” name=hiddenIFrame />
you can also search in google as "hidden iframe submit"
I want to send a message to the server comprises of a few different sections. The goal is to send some x-www-form-urlencoded info with an image. I tried do sth similiar to this: http://en.wikipedia.org/wiki/MIME#Multipart_messages
This is my js function to do that:
function sendPage() {
var source = document.getElementById("pageContainer")
var serializer = new XMLSerializer
if (!source.hasChildNodes()) {
alert("nie ma nic do wysłania")
return
}
var DOMNodeInString = "content=" + escape(serializer.serializeToString(source))
// sendToServer("savePage.php", true, handleAndShow, DOMNodeInString);return
xhttp.open("POST", "savePage.php", true)
var boundary = "xxx"
var body = "--" + boundary + "\r\n"
var file = document.getElementById("imgSource").files[0]
//wysyłam obrazek
if (file) {
var reader = new FileReader()
reader.readAsBinaryString(file)
body += "Content-Disposition: form-data; name='upload'; filename='" + file.name + "'\r\n"
body += "Content-Type: application/octet-stream\r\n\r\n"
body += reader.result + "\r\n"
body += "--" + boundary + "\r\n"
}
//wysyłam pozostałe pola formularza
body += "Content-Type: multipart/x-www-form-urlencoded \r\n\r\n"
body += DOMNodeInString
body += "\r\n--" + boundary + "--"
xhttp.setRequestHeader("Content-Type", "multipart/mixed; boundary=" + boundary)
xhttp.onreadystatechange = handleAndShow
alert(body)
xhttp.send(body)
}
however, the function doesn't work. My php script is unable to receive $_POST["content"]. What should I change to improve the js script?
It is not possible to upload a file using an XMLHttpRequest. You'll need to use Flash/Java or create a hidden iframe and do an actual submit. I'd suggest using a javascript plugin for "AJAX" file upload.
Apart from #tvanfosson answer, you are missing a creation of the xhttp object:
var xhttp = new XMLHttpRequest();
Use any debugger to see that the JS works without exceptions...
How can I create a HTTP request that sends one file and some post data with JavaScript that can be received by a PHP server?
I have found the following suggestion but it does not seem to be complete
xhr.open("POST", "upload.php");
var boundary = '---------------------------';
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
xhr.setRequestHeader("Content-Type", 'multipart/form-data; boundary=' + boundary);
var body = '';
body += 'Content-Type: multipart/form-data; boundary=' + boundary;
//body += '\r\nContent-length: '+body.length;
body += '\r\n\r\n--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="';
body += 'myfile"; filename="'+file.fileName+'" \r\n';
body += "Content-Type: "+file.type;
body += '\r\n\r\n';
body += file.getAsBinary();
body += '\r\n'
body += '--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="submitBtn"\r\n\r\nUpload\r\n';
body += '--' + boundary + '--';
xhr.setRequestHeader('Content-length', body.length);
To get this working I need to have a 'file' variable that contains an input type file field but where to put additional post data? I want to send a description text as well. suppose I would also need to use xhr.send to send the request...
Additional POST data should be placed as another Content-Disposition. Example:
Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="submit-name"
Larry
--AaB03x
Content-Disposition: form-data; name="files"; filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--AaB03x--
Here two variables are sent: the file to be uploaded and a input with name = "submit-name" and value Larry. You could have as many Content-Dispositions as variables you would like to POST.
Of course much of the plumbing could be simplified if you used a js framework like jQuery. Here's an excellent plugin which should do the job.
Why not use jquery? It save you setting up your own XHR request.
AFAIK It's not possible to send files with XmlHttpRequest.