I have an application with Node.js, Express.js , MongoDB and Javascript for front-end. I want to create file upload to add image . I use formidable and use AWS like cloud platform to save images too.
The problem is :
In my application , I have a form for add information about a car , for example: mark, model, year, location ,price, Choose image button and Submit button. When I fill the fields with data and choose image , then click on Submit button, in the console it write this:
Error: Request aborted
at IncomingMessage.<anonymous> (C:Users201217040DocumentsCarRentalnode_modulesformidablelibincoming_form.js:122:19)
at IncomingMessage.emit (node:events:369:20)
at IncomingMessage.emit (node:domain:470:12)
at abortIncoming (node:_http_server:598:9)
at socketOnClose (node:_http_server:589:3)
at Socket.emit (node:events:381:22)
at Socket.emit (node:domain:470:12)
at TCP.<anonymous> (node:net:666:12)
I put part of app.js :
const express = require('express');
const exphbs = require('express-handlebars');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const passport = require('passport');
const bcrypt = require('bcryptjs');
const formidable = require('formidable');
const socketIO = require('socket.io')
// init app
const app = express();
// setup body parser
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
// configuration for autthentication
app.use(cookieParser());
app.use(session({
secret: 'mysecret',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
// load helpers
const {requireLogin, ensureGuest} = require('./helpers/authHelper');
const {upload} = require('./helpers/aws');
// load passports
require('./passport/local');
require('./passport/facebook.js');
// receive image
app.post('/uploadImage',requireLogin,upload.any(),(req,res)=>{
const form = new formidable.IncomingForm();
form.on('file',(field,file)=>{
console.log(file);
});
form.on('error',(err)=>{
console.log(err);
});
form.on('end',()=>{
console.log('Image received successfully.');
});
form.parse(req);
});
Here is where I add “upload” in aws.js :
const aws = require('aws-sdk');
const multer = require('multer');
const multers3 = require('multer-s3');
const keys = require('../config/keys');
aws.config.update({
accessKeyId:keys.AWSAccessID,
secretAccessKey: keys.AWSSecretKey,
region: 'eu-north-1'
});
const s3 = new aws.S3({});
const upload = multer({
storage: multers3({
s3:s3,
bucket: 'car-rental-application',
ac1:'public-read',
metadata:(req,file,cb)=>{
cb(null,{fieldName:file.fieldname});
},
key: (req,file,cb)=>{
cb(null,file.originalname);
},
rename: (fieldName,fileName) =>{
return fileName.replace(/W+/g, '-').toLowerCase();
}
})
});
exports.upload = upload;
And here is html form:
<div class="row">
<div class="col-sm"></div>
<div class="col-sm-5">
<form action="/listCar2" method="POST">
<input type="hidden" name="carID" value="{{car._id}}">
<div class="form-group">
<label for="pricePerHour">Price per hour</label>
<input type="number" name="pricePerHour" id="pricePerhour" class="form-control" required>
</div>
<div class="form-group">
<label for="pricePerWeek">Price per week</label>
<input type="number" name="pricePerWeek" id="pricePerWeek" class="form-control" required>
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" name="location" id="location" class="form-control" placeholder="street, city, state and zipcode " required>
</div>
<div class="form-group">
<button class="btn btn-info upload-btn" type="button">Choose image</button>
<input type="file" name="image" id="upload-input" style="display: none;" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">List a car</button>
</div>
</form>
</div>
<div class="col-sm"></div>
</div>
<script src="https://code.jquery.com/jquery-3.6.4.js" integrity="sha256-a9jBBRygX1Bh5lt8GZjXDzyOB+bWve9EiO7tROUtj/E=" crossorigin="anonymous"></script>
<script>
// fetch location using javascript
function initMap(){
var location = document.getElementById('location');
var Autocomplete = new google.maps.places.Autocomplete(location);
}
// jquery code starts here
$(document).ready(function(){
$('.upload-btn').on('click',function(){
$('#upload-input').click();
});
$('#upload-input').on('change', function(){
var uploadInput = $('#upload-input');
if(uploadInput.val() != ''){
var formData = new FormData();
formData.append('image', uploadInput[0].files[0]);
// make ajax request to send image to database
$.ajax({
url: '/uploadImage',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function() {
uploadInput.val('');
}
})
}
})
})
</script>
<script async
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCZa44WBMahTn9Zf2z9x6fKiZTMQQh3vbw&libraries=places&callback=initMap"></script>
How can I fix this problem?