![PyPI Now Supports iOS and Android Wheels for Mobile Python Development](https://cdn.sanity.io/images/cgdhsj6q/production/96416c872705517a6a65ad9646ce3e7caef623a0-1024x1024.webp?w=400&fit=max&auto=format)
Security News
PyPI Now Supports iOS and Android Wheels for Mobile Python Development
PyPI now supports iOS and Android wheels, making it easier for Python developers to distribute mobile packages.
express-form-post
Advanced tools
A simple and efficient solution to handling file and form submissions
Note: This module works in any node.js setting. Express is not required for usage.
$ npm install express-form-post --save
The information for the uploaded file will be available in the files
object in the request
object. Fields that were sent along the request will be available on thebody
object in the request
object. express-form-post can be dropped in as middleware or used as a function to handle file upload. Check out the samples on the github repository for more specific usage!
I only recommend using the middleware if you do not plan to handle errors in any way. I recommend using the other methods listed below.
var express = require("express");
var app = express();
var efp = require("express-form-post");
var formPost = efp();
app.use(formPost.middleware());
You can also use express-form-post's method 'upload' instead of the middleware method. It is a more intuitive way of handling the upload. I would recommend using this if you want to handle errors in any sophisticated way (if you're doing something more than just logging the error).
var express = require("express");
var app = express();
var efp = require("express-form-post");
var formPost = efp();
app.post("/upload", function(req, res, next) {
formPost.upload(req, res, function(err) {
if(err) {
console.log(err);
}
console.log("My files are located here:", req.files);
res.redirect("/");
});
}
You can also specify a promise options in efp(opts) to use the upload method as a promise. For those that prefer using promises, this is definitely a viable option.
var express = require("express");
var app = express();
var efp = require("express-form-post");
var formPost = efp({
promise: true
});
app.post("/upload", function(req, res, next) {
formPost.upload(req, res).then(() => {
// add your response statements here
console.log("The uploaded file information is located here:", req.files);
res.redirect("/");
}).catch((err) => {
// add your catch statements here
});
}
var express = require("express");
var app = express();
var efp = require("express-form-post");
const formPost = efp({
store: "disk",
directory: path.join(__dirname, "tmp"),
maxfileSize: 10000,
filename: function(file, cb) {
cb(Date.now() + "-" + "this is the file name");
},
validateFile: function(fieldname, mimetype, cb) {
console.log(mimetype);
if(mimetype != "application/pdf") {
return cb(false);
}
return cb();
},
validateBody: function(body, cb) {
// validates password length before uploading file
if(body.password.length > 7) {
return cb(false);
}
cb();
}
});
app.post("/upload", formPost.middleware(), function(req, res, next) {
console.log("I just received files", req.files);
res.send("Upload successful!");
});
$ npm install aws-sdk --save
var express = require("express");
var app = express();
var efp = require("express-form-post");
const formPost = efp({
store: "aws-s3",
maxfileSize: 100000,
filename: function(file, cb) {
cb(file.originalname);
},
api: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.secretAccessKey,
bucketName: process.env.S3_BUCKET_NAME,
ACL: "public-read"
}
})
app.post("/upload", formPost.middleware(), function(req, res, next) {
console.log("I just received files", req.files);
res.send("Upload successful!");
});
$ npm install dropbox dropbox-stream --save
var express = require("express");
var app = express();
var efp = require("express-form-post");
const formPost = efp({
store: "dropbox",
filename: function(file, cb) {
cb(file.originalname);
},
api: {
accessToken: process.env.dropboxAccessToken
}
});
app.use(formPost.middleware(function(err) {
if(err) console.log(err);
console.log("Here are my files", req.files);
}));
When initializing an instance of efp (express-form-post) you can provide it different options that will change the way efp handles your file uploads.
express-form-post accepts an "optional" options parameter list. Keep in mind all fields are OPTIONAL. If you don't provide any, the express-form-post api will take care of that using the default options.
Key | Description | Note |
---|---|---|
store | The type of store | check below for available store methods |
directory | The folder to which the file will be saved | defaults to current directory |
promise | True if upload is to be used as a promise | Optional field. Defaults to false |
filename | function to determine file save name | defaults to the a unique 64 bit hash generated by hasha |
maxfileSize | Maximum Size of the uploaded file in bytes | defaults to infiniti |
minfileSize | Minimum Size of the uploaded file in bytes | defaults to 0 |
validateFile | function to validate uploaded file | takes params: fieldname, mimetype, callback |
validateBody | function to validate the body of the request before storing the validated file | takes params: body, callback |
api | api configuration information (api keys) | read further documentation for specifications |
One of the advantages of using express-form-post to handle file uploads is the validation api. There are two (optional) validation methods available during setup: validateFile and validateBody.
If specifying a validation method property, you must call the callback argument or your file will go unhandled.
Both validate functions were designed to be an intuitive way to create conditional file handling. In order to invalidate a request/file upload, you just need to return the callback with the argument false. Examples are listed below.
The validateBody method validates the request's body before sending off your file to the specified store. This is especially helpful for handling signups that require uploading some type of file (e.g a resume). For example, if the user signs up without filling in the proper fields, you can cancel the file upload (saves api requests and creates faster responses for errors). Here is an example with validating that a field called 'username' was sent.
const formPost = efp({
validateBody: function(body, cb) {
if(body.username == undefined) {
return cb(false);
}
cb();
}
});
The validateFile method validates the file data itself. An example use case would be checking if the file is a pdf. This particular example is listed below.
const formPost = efp({
validateFile: function(fieldname, mimetype, cb) {
if(mimetype != "application/pdf") {
return cb(false);
} else {
cb();
}
}
});
There are three different ways to handle form data with express-form-post. The three ways are available as methods in the instance of a express-form-post object.
This method is used inside routes as a function rather than middleware. This allows better readability and customizability. This function takes in three parameters : request, response, and an optional callback. The request and response object should be the ones provided by express.
This method is used as middleware and provides a good layer of abstraction for file handling.
This method is used to only parse the fields and ignore the files. I would recommend against using this and to use body-parser
instead, but fields is available for those who are not looking to download multiple modules that do the same.
Here are the different information you can input for each api storage. These options would go inside the api property of the options listed above.
Key | Description | Note |
---|---|---|
accessKeyId | AWS access key id | Optional if already set through aws.config.update. You can find it here : aws console |
secretAccessKey | secret key for aws | Optional based on your s3 settings |
bucketName | The name of your bucket. | Required |
ACL | Access control list | Privacy control. Defaults to "private" |
Key | Description | Note |
---|---|---|
accessToken | used by Dropbox to identify your app | Required Check out the docs |
clientId | Dropbox client Id | Optional |
selectUser | Specific user in a team box | Optional |
Samples are also available on the github page. Please take a look and reach out if you have any questions: github
FAQs
Simple, reliable and memory efficient http file parse and upload api
The npm package express-form-post receives a total of 3 weekly downloads. As such, express-form-post popularity was classified as not popular.
We found that express-form-post demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now supports iOS and Android wheels, making it easier for Python developers to distribute mobile packages.
Security News
Create React App is officially deprecated due to React 19 issues and lack of maintenance—developers should switch to Vite or other modern alternatives.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.