Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error in uploading a photo in javascript using a multer. #1228

Open
barbiedo opened this issue Sep 6, 2023 · 3 comments
Open

Error in uploading a photo in javascript using a multer. #1228

barbiedo opened this issue Sep 6, 2023 · 3 comments

Comments

@barbiedo
Copy link

barbiedo commented Sep 6, 2023

IMG_9989

upload photo page

const express = require('express');
const multer = require('multer');
const path = require('path');

const app = express();
const port = process.env.SERVER_PORT || 3000;

// Set up storage for uploaded files
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../assets/uploads');
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
const fileExtension = path.extname(file.originalname);
cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension);
}
});

const upload = multer({ storage: storage });

// Serve uploaded files statically
app.use('/uploads', express.static('uploads'));

// Handle file upload
app.post('/upload-photo', upload.single('image'), (req, res) => {
if (!req.file) {
return res.status(400).json({ message: 'No file uploaded' });
}

// You can perform additional logic here, like saving the file path to a database
// and returning a response.
const { DB_CURRENT_TIMESTAMP, queryDb } = require('@api/utils/mysql');

module.exports = async function(req, res) {
try {
const { image = '' } = req.body;

if (!image) {
return res.status(400).json({
message: 'Please select an Image.',
});
}

const imagePath = /uploads/${image.filename}; // Update the path to match your file storage location

// Save file path to the database
await queryDb(
INSERT INTO gallery (date_uploaded, image) VALUES (?, ?),
[DB_CURRENT_TIMESTAMP, imagePath]
);

return res.status(200).json({
message: 'Image Uploaded!'
});
} catch (err) {
res.status(500).json({
message: Server error : ${err.message}
});
}
};

res.status(200).json({ message: 'Image Uploaded' });
});

app.listen(port, () => {
console.log(Server is running on port ${port});
});

To connect in database
const { DB_CURRENT_TIMESTAMP, queryDb } = require('@api/utils/mysql');

module.exports = async function(req, res) {
try {
var {
// event_id = '',
// photo_name = '',
image = '',
} = req.body;
// var image = req.files && req.files.image;

  if (!image) {
      return res.status(400).json({
        message: 'Please select an Image.',
      });
  }
  // if (!event_id) {
  //     return res.status(400).json({
  //       message: 'Please provide the event Id.',
  //     });
  // }
  // if (!photo_name) {
  //     return res.status(400).json({
  //       message: 'Please provide a name for the photo.',
  //     });
  // }

  await queryDb(`
      INSERT INTO gallery (date_uploaded, image ) VALUES (?,?)`,
      [ DB_CURRENT_TIMESTAMP, image ]
  );

  return res.status(200).json ({
      message: 'Photo successfully added!'
  });

}
catch(err) {
// console.log(err.message);
res.status(500).json({
message: Server error : ${err.message}
});
}
}

@wmayo
Copy link

wmayo commented Dec 9, 2023

what's the code on your static page from below line?
app.use('/uploads', express.static('uploads'));

It could be the name of the input field is not "image".

@joeyguerra
Copy link

as you check the HTML, make sure the <form enctype="multipart/form-data"> is set.

@hagm1986
Copy link

Tenho o seguinte erro que estou com dificuldade em resolver.
image
Tendo import React from 'react';
import PropTypes from 'prop-types';
import { Box, Card, Avatar, CardMedia, Button } from '@mui/material';
import { styled } from '@mui/material/styles';

import UploadTwoToneIcon from '@mui/icons-material/UploadTwoTone';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import { RootState } from '../../../interfaces/state-interfaces';

const Input = styled('input')({
display: 'none',
});

const AvatarWrapper = styled(Card)(
({ theme }) => `

position: relative;
overflow: visible;
display: inline-block;
margin-top: -${theme.spacing(9)};
margin-left: ${theme.spacing(2)};

.MuiAvatar-root {
  width: ${theme.spacing(16)};
  height: ${theme.spacing(16)};
}

`,
);

const CardCover = styled(Card)(
({ theme }) => `
position: relative;

.MuiCardMedia-root {
  height: ${theme.spacing(26)};
}

`,
);

const CardCoverAction = styled(Box)(
({ theme }) => position: absolute; right: ${theme.spacing(2)}; bottom: ${theme.spacing(2)};,
);
interface ProfileCoverProps {
handleFileChange: () => void;
submitFile: () => void;
}
const ProfileCover = ({ handleFileChange, submitFile }: ProfileCoverProps) => {
const { t } = useTranslation('dashboard-user');
const { user } = useSelector((state: RootState) => state.user);

return (
<>





<Button
startIcon={}
variant="contained"
component="span"
onClick={() => {
submitFile();
}}
>
{t('change.cover')}







</>
);
};

ProfileCover.propTypes = {
// @ts-ignore
user: PropTypes.object.isRequired,
};

export default ProfileCover;
Tendo o controller async photoUser(req: any, res: any) {
try {
if (!req.file) {
throw new Error('Missing file!');
}
const imageBlob = req.files.file.data;
//const mimetype = req.files.file.mimetype;
//const tag = 'data:' + mimetype + ';base64,' + imageBlob;

  const userDetail = await this.user.getUserDetails(req.session.user.id);
  userDetail.blob = imageBlob;

  // Update User
  const userNewDetail = await this.user.patchUser(
    userDetail.json,
    req.session.user.email,
  );
  const user = userNewDetail.json;
  user['blob'] = userDetail.blob; // add blob to response
  res.status(200).send(user);
} catch (error) {
  Core.log_fatal('BaseController', error.message);
  res.status(500).send(error.message);
}

}Como resolver o Missing file!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants