I am using Vuetify in my VueJs project and I need to send data from my form in which I am uploading a file (CSV) and got some number inputs. I need to do that with Axios.
I've tried to do something but always got a 404.
This is my Vuetify code:
<v-form>
<v-container>
<v-row>
<v-file-input
show-size
counter
multiple
label="Nacitaj CSV"
ref="myfile"
v-model="files"
></v-file-input>
</v-row>
<v-row>
<v-col>
<v-text-field
type="number"
label="zadaj cislo"
/>
</v-col>
<v-col>
<v-text-field
type="number"
label="zadaj cislo"
/>
</v-col>
</v-row>
<v-row>
<v-col :cols="2">
<v-btn
block
color="primary"
#submit="submitFiles"
>
Submit
</v-btn>
</v-col>
</v-row>
</v-container>
</v-form>
methods: {
submitFiles() {
if (this.files) {
let formData = new FormData();
// files
for (let file of this.files) {
formData.append("files", file, file.name);
}
// additional data
formData.append("test", "foo bar");
axios.post("/about", formData);
}
I've tried the script which I found on internet but it wasn't working; also the script was only for the file.
I know this is super old but for the next person arriving at this answer, let's take a look at submitFiles function:
submitFiles() {
if (this.files) {
let formData = new FormData();
// files
for (let file of this.files) {
formData.append("files", file, file.name);
}
// additional data
formData.append("test", "foo bar");
axios.post("/about", formData);
}
the first if is checking if files is not empty. files is part of the model. If there are files it creates a new object to hold the Form data (formData).
Then it will loop the files object and append the files to the object holding the form data and after that it will append a field called test with the value foo bar and make a post request to /about in the domain you're serving your page sending the form data object as the body. If you're getting a 404 it should mean that about doesn't exist.
Related
I would like to create a form that allows anyone to upload multiple files to my drop box. But I would also like for the person that uploads the file to receive a confirmation email. The following code uploads the files but does send the email. Please help!
Here is the .gs
function doGet(e) {return HtmlService.createHtmlOutputFromFile('form.html');}
function sendEmails(form) {
var message= ", your abstract was submitted. Send other work by APR 20";
var subject = "Application Received";
MailApp.sendEmail(form.myEmail, subject, message);
}
function uploadFiles(form) {
try {
var dropbox = "New Abstracts";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile1;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
var blob = form.myFile2;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
return "File uploaded successfully " + file.getUrl();
} catch (error) {
return error.toString();
}
}
And here is the .html portion
<form id="myForm">
<input type="text" name="myName" placeholder="Your name..">
<input type="email" name="myEmail" placeholder ="Your email..">
<input type="file" name="myFile1" >
<input type="file" name="myFile2" >
<input type="submit" value="Upload File"
onclick="this.value='Uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode).sendEmails(this.parentNode);
return false;">
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
I trying this based on the codes found at:
http://www.labnol.org/internet/receive-files-in-google-drive/19697/
You can't append multiple calls to the script like this:
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode).sendEmails(this.parentNode);
Only uploadFiles (the first one being called) gets executed. Everything after that is getting ignored.
You can add the code inside sendEmails() to the uploadFiles() as one solution? Or add it to the success handler? Or have uploadFiles() call sendEmails() once it is done...
I have got a set 3 HTML Pages
I am using Apache Tomcat 7 server . I have got the following HTML pages (All are HTML pages only)
login.html
sales.html
index.html
The code for the login.html is when clicked on submit is
<input type="email" name="email" id="email" >
<input type="pin" name="email" id="pin" >
<button class="primary login-btn">Submit</button>
Once clicked on Submit button , i am calling a Jersey REST Webservce this way and will response either true OR false based on the values present in our Database
function submitLoginForm() {
var email_input = $.trim($("#email").val());
var pin_input = $.trim($("#pin").val());
var logininfo = {
'email': email_input,
'pin': pin_input
};
var login_information = JSON.stringify(logininfo);
$.ajax({
type: 'POST',
dataType: 'json',
data: login_information,
url: url + '/HEGS/orn/webchecklogin',
success: function(response) {
// if true , redirect to sales.html page
window.location = "index.html"
},
});
}
All this is working fine , my issue is , how can i stop the prevent the user from accessing the page directly
For example if he types the follwing URL
http:localhost:8080/HEGS/dealer/sales.html
You would want to redirect the url to one file, which would then load the correct file based on the criteria you set. I don't know much about Tomcat, but this article seems to explain it well under the "URL Rewriting" section.
So I do want to say that I've been searching for the answer for this and I've also tried to console.log my req.body post form and I keep getting undefined. So I feel that I'm losing the data from the form I send, I'm not sure what I"m doing wrong. So time to show some code.
As a note: I am using Handlebars for my Express Setup.
app.js
var express = require('express'),
exphbr = require('express3-handlebars'), // "express3-handlebars"
nodemailer = require('nodemailer'),
helpers = require('./lib/helpers'),
app = express(), handlebars;
// Create `ExpressHandlebars` instance with a default layout.
handlebars = exphbr.create({
defaultLayout: 'main',
helpers : helpers,
extname : '.html',
// Uses multiple partials dirs, templates in "shared/templates/" are shared
// with the client-side of the app (see below).
partialsDir: [
'views/shared/',
'views/partials/'
]
});
// Register `hbs` as our view engine using its bound `engine()` function.
app.engine('html', handlebars.engine);
app.set('view engine', 'html');
require("./routes")(app, express, nodemailer);
app.listen(3000);
routes.js
module.exports = function (app, express, nodemailer) {
// set up the routes themselves
app.get('/', function (req, res) {
res.render('home', {
title: 'Larry King Orchestra'
});
});
// I cut out a majority of my routes to make this easier to read.
// SEND EMAIL FROM FORM
app.post('/', function (req, res) {
console.log("WTF");
console.log(req.body.name);
console.log(req.body.email);
var mailOpts, smtpTrans;
//Setup nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
smtpTrans = nodemailer.createTransport('SMTP', {
service: 'Gmail',
auth: {
user: "email#gmail.com",
pass: "password"
}
});
//Mail options
mailOpts = {
from: req.body.email, //grab form data from the request body object
to: 'anotheremail#gmail.com',
subject: 'LKO Contact Form',
html: 'From: ' + req.body.name + ' <' + req.body.email + '> <br>Phone: ' + req.body.tel + '<br>Date of Event: ' + req.body.date + '<br>Location: ' + req.body.location + '<br>Details & Comments:<br>' + req.body.message + '<br><br><p>Email form provided by WavaMedia.'
};
smtpTrans.sendMail(mailOpts, function (error, response) {
//Email not sent
if (error) {
res.render('home', {
title: 'Larry King Orchestra',
msg: 'Error occured, message not sent.',
err: true,
page: 'home'
});
}
//Yay!! Email sent
else {
res.render('home', {
title: 'Larry King Orchestra',
msg: 'Message sent! Thank you.',
err: false,
page: 'home'
});
}
});
});
// STATIC ROUTE FOR ASSESTS
app.use(express.static('assests/'));
};
I renamed the handlebars extension to be .html and I have the main layout using partials. SO app.get('/') will show this next file as a partial, and render it on the page.
contact.html
<form class="contact" action="/" method="post">
<label for="name">Name</label>
<input type="name" name="name" id="name">
<label for="email">Your Email (required)</label>
<input type="email" name="email" id="email">
<label for="tel">Phone Number</label>
<input type="tel" name="tel" id="tel">
<label for="date">Date of Your Event</label>
<input type="date" name="date" id="date">
<label for="location">Venue/Location</label>
<input type="location" name="location" id="location">
<label for-"message">Details & Comments</label>
<textarea name="message" id="message" rows="3"></textarea>
<input type="submit" name="submit" id="submit" value="Send" class="btn btn-default">
</form>
My Error:
TypeError: Cannot read property 'name' of undefined at c:\xampp\htdocs\lko\routes.js:129:26 at callbacks (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:164:37) at param (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:138:11) at pass (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:145:5) at Router._dispatch (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:173:5) at Object.router (c:\xampp\htdocs\lko\node_modules\express\lib\router\index.js:33:10) at next (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.expressInit [as handle] (c:\xampp\htdocs\lko\node_modules\express\lib\middleware.js:30:5) at next (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.query [as handle] (c:\xampp\htdocs\lko\node_modules\express\node_modules\connect\lib\middleware\query.js:45:5)
So I'm not sure where I'm going wrong with the code. I believe the form is sending data to my node app, but where it's going, I'm not sure. I've setup the post method and so far no luck :( I have been trying for a couple days now. I have nodemailer installed as well. I've restarted the server, updated node and npm.
JavaScript Node Guru Masters, only you can show me the light! And thanks for reading though all of this, totally awesome!
app.use(express.bodyParser());
add that to your app.js
that's what grabs information from the post data form.
You have to require body parser package for this.
At first you have to install it with npm.
$ npm install --save body-parser
Then require that in your js file.
var bodyParser = require('body-parser');
Then add the parser. As you are using html post method it uses urlencoded as encoding type. For that add this line.
var urlencodedParser = bodyParser.urlencoded({ extended: false });
(If you use json you must use bodyParser.json() instead of this)
Now add the parser with the encoding type to app.post method as follows.
app.post('/',urlencodedParser, function (req, res) {
//your code here
});
You don't have to be explicitly mention any bodyParser or bodyParer.json
Instead You can make it simple to use this because this is a built-in middleware function in Express.
app.use(express.json());
app.use(bodyparser.urlencoded({extended : true }));
I am new to these technologies and hence have limited knowledge on how to upload a file. During my research, I have seen ngUpload and other javascript/directive based solutions. However, I am trying the following and not sure what else I am missing to complete it.
I am trying to upload file after creating a blog using angular-express-blog application. I have the following code
In view.jade
fieldset
h5 Add Media
form(name='theForm', enctype="multipart/form-data")
.clearfix
label Document Name
.input: input(ng-model='form.docName', name='docName', type='text')
.clearfix
label File
.input: input(ng-model='form.file', type="file", name="file")
.actions
button(ng-click="uploadFiles('/page3files')") Upload Files
the controller, I do need to return to the uploadfile page hence, I am passing in /page3files.
$scope.uploadFiles = function( path ) {
//alert("upload files clikced");
$http.post('/api/uploadFile', $scope.form).
success(function(data) {
$scope.form.docName='';
$scope.form.file='';
$location.path(path);
});
};
In the express routes file
exports.uploadFile = function (req, res) {
console.log("doc name: " + req.body.docName);
console.log("file name: " + req.body.file.name);
console.log("file path: " + req.body.file.path);
res.json(true);
};
Unfortunately, I am getting an exception at req.body.file.name saying cannot read property 'name' of undefined.
Any assistance is much appreciated.
Thanks,
Melroy
for the $http.post() to be able to upload files you need to set some configurations.
headers : {'Content-Type': undefined},
transformRequest: angular.identity
You can use the simple/lightweight angular-file-upload directive that takes care of that for you.
It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim.
<div ng-controller="MyCtrl">
<input type="file" ng-file-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directive.
angular.module('myApp', ['angularFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$upload.upload({
url: 'my/upload/url',
file: $file,
progress: function(e){}
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
}
}];
There are more info on the README page and there is a Demo page
You can send file data with FormData object. For Example:
HTML:
<fieldset>
<legend>Upload Video</legend>
<input type="file" name="photo" id="photo">
<input type="button" ng-click="uploadVideo()" value="Upload">
</fieldset>
JS:
$scope.uploadVideo = function () {
var photo = document.getElementById("photo");
var file = photo.files[0];
var fd = new FormData(); //Create FormData object
fd.append('file', file);
$http.post('/uploadVideo', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data) {
// Do your work
});
};
This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 2 years ago.
I am doing project Online Image Gallery, in which I have to upload images. I am doing it with jsp/servlet and IDE is Eclipse.
My Jsp file is as follows
<form action="ActionPage" >
<input type="file" name="myFile">
<br>
<input type="submit">
</form>
Here Actionpage is servlet. On Clicking submit button i want the selected file to be stored inside the folder called "IMAGE" inside the WebContent on server and path on database table.
If any one know the simple solution please share it.
Thanks in advance.
You can read how this is done here
How to upload files to server using JSP/Servlet?
PS: Storing uploaded files inside the applications directory is BAD BAD BAD idea. Think about what would happen if you have your application running for some time, and you want to do a redeploy becase a file is missing some html tag. The upload's directory will be removed by your container!
Try using a folder outside of the application's directory, or use a database.
This is the easiest solution if You are using jsp to develop your website
First of all for taking input from user make a html or jsp page and include tis code in your jsp/html page
First of all download
commons-fileupload-1.2.2.jar
org.apache.commons.io.jar
and add this jar to your library by right-clicking your project then select build path and then add jar files
`<form role="form" action="Upload.jsp" method="post"enctype="multipart/form-data">
<div class="btn btn-success btn-file">
<i class="fa fa-cloud-upload"></i>
Browse
<input type="file" name="file" />
</div>
<button type="submit" value="submit" name='submit'>submit</button>`
</form>
enctype="multipart/form-data"
it is necessary
Now make one jsp named upload.jsp( you can have the target jsp with which we are going to save our image to server of any name but remember to put that name in in above code
<%# page import="java.io.*,java.util.*, javax.servlet.*" %>
<%# page import="javax.servlet.http.*" %>
<%# page import="org.apache.commons.fileupload.*" %>
<%# page import="org.apache.commons.fileupload.disk.*" %>
<%# page import="org.apache.commons.fileupload.servlet.*" %>
<%# page import="org.apache.commons.io.output.*" %>
<%
String userName = (String) session.getAttribute("User");
File file ;
int maxFileSize = 5000000 * 1024;
int maxMemSize = 5000000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("C:\\Users\\"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List<FileItem> fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
request.setAttribute("Success", "Successfully Uploaded");
RequestDispatcher rd = request.getRequestDispatcher("/UploadFiles.jsp");
rd.forward(request, response);
}
}
}catch(Exception ex) {
System.out.println(ex);
}
}else{
request.setAttribute("Error", "Error!!");
RequestDispatcher rd =request.getRequestDispatcher("/UploadFiles.jsp");
rd.forward(request, response);
}
%>
please don't get confused just copy this code and once you go through this i am sure you will get to know about code
Now the last thin you have to do is to add something to web.xml if you don't have this file then create this...
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
C:\\Users\\
</param-value>
</context-param>
just add above code to web.xml you can change the address where your images will be uploaded as desired ( change param-value for this)
In case you face any problem let me know