Uploading file with javascript

Upload a File in JavaScript

HTML has a file input tag that lets users select one or more files to upload. For example, below is HTML that defines a file input .

Given an , you can access the selected file as a blob by accessing input.files[0] :

const input = document.querySelector('input[type="file"]'); const file = input.files[0]; file instanceof File; // true file instanceof Blob; // true

Uploading a File

Once you have a blob, you can upload it using JavaScript’s built-in FormData class. Axios supports HTTP POST requests with FormData , so uploading a file is easy:

const formData = new FormData(); formData.append('myimage.png', file); // Post the form, just make sure to set the 'Content-Type' header const res = await axios.post('/upload', formData, < headers: < 'Content-Type': 'multipart/form-data' > >);

Server-Side Setup

Parsing FormData uploads on the server side is tricky, you should use an npm module like Formidable to help you out. Below is how you can write the corresponding POST /upload endpoint to the above Axios request.

Note that the below code just returns the file name, it doesn’t actually store the file. Once you have the parsed file in Node.js, you would need to either upload the file to AWS S3 or some other storage service, or store it on your server’s hard drive using fs .

app.post('/upload', function(req, res) < const form = new formidable.IncomingForm(); // Parse `req` and upload all associated files form.parse(req, function(err, fields, files) < if (err) < return res.status(400).json(< error: err.message >); > const [firstFileName] = Object.keys(files); res.json(< filename: firstFileName >); >); >);

For example, here’s an upload endpoint that uploads the file to a bucket named ‘masteringjs-test’ in AWS S3:

const AWS = require('aws-sdk'); app.post('/upload', function(req, res) < const form = new formidable.IncomingForm(); // Parse `req` and upload all associated files form.parse(req, function(err, fields, files) < if (err) < return res.status(400).json(< error: err.message >); > const [firstKey] = Object.keys(files); const upload = < Bucket: 'masteringjs-test', Body: fs.createReadStream(files[firstKey].path), Key: files[firstKey].name >; s3.upload(upload, (err) => < if (err) < return res.status(400).json(< error: err.message >); > return res.json(< ok: 1 >); >); >); >);

More Fundamentals Tutorials

Источник

Читайте также:  Php curl как правильно

Uploading file with javascript

  • How to maintain polyglot persistence for microservices Managing microservice data may be difficult without polyglot persistence in place. Examine how the strategy works, its challenges.
  • Top developer relations trends for building stronger teams Learn about enterprise trends for optimizing software engineering practices, including developer relations, API use, community .
  • 5 noteworthy challenges of automotive software development Modern cars are loaded with technology, but creating in-vehicle applications isn’t always a cakewalk. Here are five unique .
  • The basics of implementing an API testing framework With an increasing need for API testing, having an efficient test strategy is a big concern for testers. How can teams evaluate .
  • The potential of ChatGPT for software testing ChatGPT can help software testers write tests and plan coverage. How can teams anticipate both AI’s future testing capabilities .
  • Retail companies gain DORA metrics ROI from specialist tools DORA metrics and other measures of engineering efficiency are popping up in add-ons to existing DevOps tools. But third-party .
  • How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
  • Prices for cloud infrastructure soar 30% Tough macroeconomic conditions as well as high average selling prices for cloud computing and storage servers have forced .
  • Deploy a low-latency app with AWS Local Zones in 5 steps Once you decide AWS Local Zones are right for your application, it’s time for deployment. Follow along in this step-by-step video.
  • Orca: Google Cloud design flaw enables supply chain attacks Orca Security says threat actors can use a design flaw in Google Cloud Build’s default permissions to gain access to Artifact .
  • Microsoft still investigating stolen MSA key from email attacks While Microsoft provided additional attack details and techniques used by Storm-0558, it remains unclear how the Microsoft .
  • JumpCloud breached by nation-state threat actor JumpCloud’s mandatory API key rotation earlier this month was triggered by a breach at the hands of a nation-state threat actor .
  • AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
  • Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
  • Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .
Читайте также:  Monitor class in java

Источник

Оцените статью