Send JavaScript File() by email onclick - javascript

I have a script making a file from data (from a form or not). I have access to the URL to download the file in any browser, using window.URL.createObjectURL. But I would like to add a button to send the file by email. (I have a server and PHP).
Here is my code:
First creating File from 'test':
function makeFile(text) {
var test =
"Here is my " + text;
var data = new File([test], { type: "text/plain" });
if (myFile !== null) {
window.URL.revokeObjectURL(myFile);
}
myFile = window.URL.createObjectURL(data);
return myFile;
}
Now my unsuccessful attempt:
<form action="emailthijob.php" method="post">
<a class="download hide" id="sendbyemail" onclick="myFile.submit()";>⇧ Email</a>
</form>
So I would appreciate help with 1/button to click and send mail, 2/ PHP code to actually get the result.
Thank you very much for your help,
Best,
--Fred

Related

Pass data between two HTML pages (Google Apps Script)

I'm trying to pass var 'id' from the page 'a.html' to 'b.html'. The var content comes from 'code.gs' as below:
code.gs
function data(){
var id = 1;
return id;
}
Next, I get this var and I show it in 'a.html':
a.html
<?
var id = data();
?>
<h1><?= id ?></h1>
Go to B.html
By clicking 'Go to B.html', the system directs the user to there. I need to bring the same value of var 'id' from the page 'a.html' to 'b.html'.
Ps: searching for a little, I saw that there's a kind to send this var by the command 'localStorage', but it's not working for me. :(
Can anybody help me?
Use localstorage
a.html
localStorage.setItem('id',1)
b.html
var id = localStorage.getItem('id')
the other way is to put it in a js file and import it in both html
Storing & Retrieving html data on the server
Client Side JavaScript:
<script>
function saveId(v) {
google.script.run.saveKeyValue({key:'id',value:v});
}
function getId() {
google.script.run
.withSuccessHandler(function(v){
alert('The value is ' + v );
})
.getKeyValue('id');
}
</script>
Server Side Google Apps Script:
function saveKeyValue(obj) {
PropertiesService.getScriptProperties().setProperty(obj.key,obj.value);
}
function getKeyValue(key) {
return PropertiesService.getScriptProperties().getProperty(key);
}
You could also replace PropertiesService with CacheService.
Client To Server Communications
Properties Service

How do I run a .php function file from a .js file

How do I send data from a JavaScript file to a PHP file so that it does what it needs to do in the PHP server side. I want to send a SMS and my JavaScript is reading all the data that is coming though so all that is left is that my PHP activates and sends the data in a SMS which is already done with my PHP file. I just need to make them connect to be able to send.
Can PHP handle functions? That is what I am trying to do here by sending the data to a function in PHP from my .js file. If not, how do I send them via post?
.js file:
render : function(template,params){
var arr = [];
switch(template){
case 'smsLine':
arr = [
'<div class=" sms-',params.id,' rounded"><span class="gravatar"><img src="',params.gravatar,
'" width="23" height="23" onload="this.style.visibility=\'visible\'" />',
'</span><span class="author">',params.author,
':</span><span class="text">',params.text,
':</span><span class="text">',params.to,
'</span><span class="time">',params.time,'</span></div>'];
///////////////////////////////HERE/////////////////////////////////
//this is where I want to use a function that is in a php file
sendSMS(params.author, params.text, params.time, params.to);
///////////////////////////////HERE////////////////////////////////
break;
}
return arr.join('');
}
This is the function that I want to use in my PHP file.
.php file:
function sendSMS($from, $message, $time, $to){
$objGsm = new COM("AxSms.Gsm", NULL, CP_UTF8 );
$objGsm->LogFile = sys_get_temp_dir()."Gsm.log";
//Windows default: 'C:\Windows\Temp\Gsm.log'
//Form submitted
$obj;
$strMessageReference;
$objSmsMessage = new COM("AxSms.Message", NULL, CP_UTF8 );
$objSmsConstants = new COM("AxSms.Constants" , NULL, CP_UTF8 );
$strName = 'Modem';
$strPincode = '';
$strRecipient = '$number';
$iDeviceSpeed = '0';
$objGsm->Clear();
$objGsm->LogFile = '';
$objGsm->Open($strName, $strPincode, $iDeviceSpeed);
if ($objGsm->LastError != 0){
$strResult = $objGsm->LastError . ": " . $objGsm->GetErrorDescription($objGsm->LastError);
$objGsm->Close();
}
else{
//Message Settings
$objSmsMessage->Clear();
$objSmsMessage->ToAddress = $to;
$objSmsMessage->Body = $message;
$objSmsMessage->DataCoding = $objSmsConstants->DATACODING_UNICODE;
//Send the message !
$obj = $objSmsMessage;
$objGsm->SendSms($obj, $objSmsConstants->MULTIPART_ACCEPT, 0);
$objSmsMessage = $obj;
$strResult = $objGsm->LastError . ": " . $objGsm->GetErrorDescription($objGsm->LastError);
$objGsm->Close();
}
}
If you pull in jQuery to your front-end, you'll be able to send an AJAX request to execute that PHP function for you. it would look something like this (inserted straight into that sendSMS section in the .js code:
$.ajax() {
url: "/send/sms",
type: "POST",
data: {
author: params.author,
text: params.text,
time: params.time,
to: params.to,
}
}
Now what you will have to do is create the file for the AJAX request to be sent to, they call this an "end point". In my example I set the path of this file to being /send/sms, so perhaps you have a directory called "send" where you could send off an email or SMS, etc. For each of those methods you would have a PHP file containing the logic for it. So for this example, create an sms.php file inside YOUR_ROOT_DIRECTORY/send .
Once you send an AJAX request to that file, the PHP function will be executed. To fetch the given data, use $_POST['author'], $_POST['text'], etc.

How to upload base64 image resource with dropzone?

I'm trying to upload generated client side documents (images for the moment) with Dropzone.js.
// .../init.js
var myDropzone = new Dropzone("form.dropzone", {
autoProcessQueue: true
});
Once the client have finished his job, he just have to click a save button which call the save function :
// .../save.js
function save(myDocument) {
var file = {
name: 'Test',
src: myDocument,
};
console.log(myDocument);
myDropzone.addFile(file);
}
The console.log() correctly return me the content of my document
data:image/png;base64,iVBORw0KGgoAAAANS...
At this point, we can see the progress bar uploading the document in the drop zone but the upload failed.
Here is my (standart dropzone) HTML form :
<form action="/upload" enctype="multipart/form-data" method="post" class="dropzone">
<div class="dz-default dz-message"><span>Drop files here to upload</span></div>
<div class="fallback">
<input name="file" type="file" />
</div>
</form>
I got a Symfony2 controller who receive the post request.
// Get request
$request = $this->get('request');
// Get files
$files = $request->files;
// Upload
$do = $service->upload($files);
Uploading from the dropzone (by drag and drop or click) is working and the uploads are successfull but using the myDropzone.addFile() function return me an empty object in my controller :
var_dump($files);
return
object(Symfony\Component\HttpFoundation\FileBag)#11 (1) {
["parameters":protected]=>
array(0) {
}
}
I think i don't setup correctly my var file in the save function.
I tryied to create JS image (var img = new Image() ...) but without any success.
Thanks for your help !
Finally i found a working solution without creating canvas :
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
And the save function :
function save(dataURI) {
var blob = dataURItoBlob(dataURI);
myDropzone.addFile(blob);
}
The file appears correctly in dropzone and is successfully uploaded.
I still have to work on the filename (my document is named "blob").
The dataURItoBlob function have been found here : Convert Data URI to File then append to FormData
[EDIT] : I finally wrote the function in dropzone to do this job. You can check it here : https://github.com/CasperArGh/dropzone
And you can use it like this :
var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAAKwCAYAAA...';
myDropzone.addBlob(dataURI, 'test.png');
I can't comment currently and wanted to send this to you.
I know you found your answer, but I had some trouble using your Git code and reshaped it a little for my needs, but I am about 100% positive this will work for EVERY possible need to add a file or a blob or anything and be able to apply a name to it.
Dropzone.prototype.addFileName = function(file, name) {
file.name = name;
file.upload = {
progress: 0,
total: file.size,
bytesSent: 0
};
this.files.push(file);
file.status = Dropzone.ADDED;
this.emit("addedfile", file);
this._enqueueThumbnail(file);
return this.accept(file, (function(_this) {
return function(error) {
if (error) {
file.accepted = false;
_this._errorProcessing([file], error);
} else {
file.accepted = true;
if (_this.options.autoQueue) {
_this.enqueueFile(file);
}
}
return _this._updateMaxFilesReachedClass();
};
})(this));
};
If this is added to dropzone.js (I did just below the line with Dropzone.prototype.addFile = function(file) { potentially line 1110.
Works like a charm and used just the same as any other. myDropzone.addFileName(file,name)!
Hopefully someone finds this useful and doesn't need to recreate it!
1) You say that: "Once the client have finished his job, he just have to click a save button which call the save function:"
This implies that you set autoProcessQueue: false and intercept the button click, to execute the saveFile() function.
$("#submitButton").click(function(e) {
// let the event not bubble up
e.preventDefault();
e.stopPropagation();
// process the uploads
myDropzone.processQueue();
});
2) check form action
Check that your form action="/upload" is routed correctly to your SF controller & action.
3) Example Code
You may find a full example over at the official Wiki
4) Ok, thanks to your comments, i understood the question better:
"How can i save my base64 image resource with dropzone?"
You need to embedd the image content as value
// base64 data
var dataURL = canvas.toDataURL();
// insert the data into the form
document.getElementById('image').value = canvas.toDataURL('image/png');
//or jQ: $('#img').val(canvas.toDataURL("image/png"));
// trigger submit of the form
document.forms["form1"].submit();
You might run into trouble doing this and might need to set the "origin-clean" flag to "true". see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#security-with-canvas-elements
how to save html5 canvas to server

django view cannot get file using request.FILES from ajax form submit

I tried to submit this form using ajax ,sothat a django view can extract the selected file from request.FILES and write to a directory on server
<form enctype="multipart/form-data" method="post" id="fileupoadform">{% csrf_token %}
<p>
<label>Select a file
<input type="file" name="fselect" id="fselect"> </input>
</label>
</p>
<input type="submit" value="upload">
</form>
the view is
def ajax_upload(request):
print 'ajax_upload()'
print 'request=',request
to_return = {}
store_message="failure"
if (request.is_ajax()) and (request.method == 'POST'):
print 'is ajax and post'
print 'request.FILES=',request.FILES
if request.FILES.has_key('fselect'):
print "request has key='fselect'"
file = request.FILES['fselect']
with open(settings.UPLOADPATH'%s' % file.name, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
store_message="success"
to_return['store_message']= store_message
print 'to_return=',to_return
to_return['store_message']= store_message
serialized = simplejson.dumps(to_return)
print 'serialized=',serialized
if store_message == "success":
print 'suceessfully returning'
return HttpResponse(serialized, mimetype="application/json")
else:
print 'failed!! returning'
return HttpResponseServerError(serialized, mimetype="application/json")
I used jquery to make the ajax submit
$(document).ready(function(){
$('#fileupoadform').submit(function(e){
submitUploadForm(e);
});
});
function submitUploadForm(e){
console.log('clicked submit');
e.preventDefault();
var file = $('#fselect').get(0).files[0];
console.log('filename='+file.name)
var data = { name:file.name };
var args = { type:"POST", url:"upload/", data:data, complete:doneAjaxUpload };
$.ajax(args);
}
when I tried this ,I got this console output
ajax_store_uploaded_file()
request= <WSGIRequest
GET:<QueryDict: {}>,
POST:<QueryDict: {u'name': [u'myfile.srt']}>,
COOKIES:{'csrftoken': 'ca367878345fa9e59adf79hg047a1dvb'},
...
is ajax and post
request.FILES= <MultiValueDict: {}>
to_return= {'store_message': 'failure'}
serialized= {"store_message": "failure"}
failed!! returning
[01/Jun/2012 11:27:26] "POST /myapp/upload/ HTTP/1.1" 500 28
I sense that I am doing something wrong in the django view..Is it that I cannot get the uploaded file from request.FILES.In a non ajax version of django view ,I was able to get the file from request.FILES using request.FILES['fselect']
Can somebody help me resolve this?
I don't think you can do ajax file uploads (easily).
Certainly, it doesn't look like you're actually passing a file to your post data, you're just passing the file name -
var data = { name:file.name };
Check out this question for plugins / info to help do this - How can I upload files asynchronously?

Upload the image with preview

Hi I wanted to upload images(along with other form details) and preview them, using jsp and servlets. I am able to do the uploading part but could not get, how to preview the images in the frontend.
I am using YUI to implement it. Actually I am trying to reuse an example which is implemented in PHP. I am attaching my Servlet code here. In this 'completeFileName' will be populated when a upload has been done.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(completeFileName == null) {
PrintWriter pout = response.getWriter();
JSONObject obj = new JSONObject();
obj.put("hasError", new Boolean(true));
pout.println(obj.toString());
}
try {
OutputStream out = response.getOutputStream();
Image image = Toolkit.getDefaultToolkit().getImage(completeFileName);
ImageIcon icon = new ImageIcon(image);
int height = icon.getIconHeight();
int width = icon.getIconWidth();
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
ImageIO.write(bi, "jpg", out);
out.flush();
} catch (Exception ex) {
}
My Jsp code looks like this:
<script type="text/javascript" src="http://yui.yahooapis.com/2.3.0/build/connection/connection.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.3.0/build/utilities/utilities.js"></script>
<script type="text/javascript">
var $E = YAHOO.util.Event;
var $ = YAHOO.util.Dom.get;
var $D = YAHOO.util.Dom;
function init(){
var listImageHandler = {
success:function(o) {
var r = eval('(' + o.responseText + ')');
if(!r.hasError) {
var imageListCon = $('imageListCon');
var img = document.createElement('img');
//img.src = 'image.php?i=' + r.imageList[i];
img.src = r.fileName;
imageListCon.appendChild(img);
}
}
};
var onUploadButtonClick = function(e){
var uploadHandler = {
upload: function(o) {
//console.log(o.responseText);
$D.setStyle('indicator', 'visibility', 'hidden');
var r = eval('(' + o.responseText + ')');
if(r.hasError){
var errorString = '';
for(var i=0; i < r.errors.length; i++){
errorString += r.errors[i];
}
alert(errorString);
}else{
YAHOO.util.Connect.asyncRequest('GET', 'UploadFileServlet', listImageHandler);
}
}
};
$D.setStyle('indicator', 'visibility', 'visible');
//the second argument of setForm is crucial,
//which tells Connection Manager this is an file upload form
YAHOO.util.Connect.setForm('testForm', true);
YAHOO.util.Connect.asyncRequest('POST', 'UploadFileServlet', uploadHandler);
};
$E.on('uploadButton', 'click', onUploadButtonClick);
YAHOO.util.Connect.asyncRequest('GET', 'UploadFileServlet', listImageHandler);
}
$E.on(window, 'load', init);
</script>
</head>
<body>
<form action="UploadFileServlet" method="POST" enctype="multipart/form-data" id="testForm">
<input type="file" name="testFile"><br>
<input type="button" id="uploadButton" value="Upload"/>
</form>
<div class="restart">Redo It</div>
<div style="visibility:hidden; margin-bottom:1.5em;" id="indicator">Uploading... <img src="indicator.gif"/></div>
<div id="imageListCon">
</div>
</body>
I am unable to get the response, can anyone help in this please ?
Thanks,
Amit
try this:
http://pixeline.be/experiments/jqUploader/
Due to security limitations, you cannot preview the image on the front-end prior to uploading
If you are already able to upload the image in a folder at your server, you can easily display the image with a image control in your page. Let that folder be a temp folder which you may wish to empty after upload is completed. Then you first upload the file in the temp folder and display it to the user. If the user cancels the operation, you can delete the file from the folder.
But remember this will not be the real image preview as we generally visualize. But since this mimics the image preview, it may be a choice.
I don't know YUI, so I can't go in detail about this, but I can at least tell that there are several flaws in your logic: you're attempting to write the entire binary contents of the image back to the ajax response. This isn't going to work. In HTML you can only display images using an <img> element whose src attribute should point to a valid URL. Something like:
<img src="/images/uploadedimage.jpg">
To achieve this, just store the image at the local disk file system or a database at the server side and give in the ajax response the URL back with which the client can access the image. Let the ajax success handler create a DOM element <img> and fill its src value with the obtained URL.
You'll need to create a Servlet which listens on this URL and get the image as an InputStream from the local disk file system by FileInputStream or from the database by ResultSet#getBinaryStream() and writes it to the OutputStream of the response, along with a correct set of response headers with at least content-type. You can find here an example of such a servlet.
That said, you really don't need the Java 2D API for that. The Image and ImageIcon only unnecessarily adds much overhead. Just get it as an InputStream and write it the usual Java IO way to the OutputStream of the response.

Categories

Resources