Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,11 +311,7 @@ Feel free to take a look at the course preview and enroll if it is along with yo
1. handle form submit
2. create updateProduct
3. save product in backend
37. Delete Product
1. update ProductListScreen.js
2. handle delete button
3. rerender after deletion
38. Upload Product Image
37. Upload Product Image
1. npm install multer
2. create routes/uploadRoute.js
3. import express and multer
Expand All @@ -332,13 +328,17 @@ Feel free to take a look at the course preview and enroll if it is along with yo
14. call uploadProductImage()
15. create uploadProductImage in api.js
16. update server.js
39. Build Project
38. Build Project
1. create build script for frontend
2. create build script for backend
3. update sever.js to serve frontend build folder and uploads folder
4. stop running frontend
5. npm run build
6. check localhost:5000 for running website and showing images
39. Delete Product
1. update ProductListScreen.js
2. handle delete button
3. rerender after deletion
40. Show Categories In Sidebar Menu
1. update ProductListScreen.js
2. handle delete button
Expand Down
20 changes: 20 additions & 0 deletions backend/routers/uploadRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import express from 'express';
import multer from 'multer';
import { isAuth, isAdmin } from '../utils';

const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, 'uploads/');
},
filename(req, file, cb) {
cb(null, `${Date.now()}.jpg`);
},
});

const upload = multer({ storage });
const uploadRouter = express.Router();

uploadRouter.post('/', isAuth, isAdmin, upload.single('image'), (req, res) => {
res.status(201).send({ image: `/${req.file.path}` });
});
export default uploadRouter;
3 changes: 2 additions & 1 deletion backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import data from './data';
import config from './config';
import userRouter from './routers/userRouter';
import orderRouter from './routers/orderRouter';
import productRouter from './routers/productRouter';
import uploadRouter from './routers/uploadRouter';

mongoose
.connect(config.MONGODB_URL, {
Expand All @@ -23,6 +23,7 @@ mongoose
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use('/api/uploads', uploadRouter);
app.use('/api/users', userRouter);
app.use('/api/products', productRouter);
app.use('/api/orders', orderRouter);
Expand Down
22 changes: 22 additions & 0 deletions frontend/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,28 @@ export const updateProduct = async (product) => {
}
};

export const uploadProductImage = async (formData) => {
try {
const { token } = getUserInfo();
const response = await axios({
url: `${apiUrl}/api/uploads`,
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
data: formData,
});
if (response.statusText !== 'Created') {
throw new Error(response.data.message);
} else {
return response.data;
}
} catch (err) {
return { error: err.response.data.message || err.message };
}
};

export const signin = async ({ email, password }) => {
try {
const response = await axios({
Expand Down
19 changes: 18 additions & 1 deletion frontend/src/srceens/ProductEditScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
showMessage,
hideLoading,
} from '../utils';
import { getProduct, updateProduct } from '../api';
import { getProduct, updateProduct, uploadProductImage } from '../api';

const ProductEditScreen = {
after_render: () => {
Expand All @@ -31,6 +31,22 @@ const ProductEditScreen = {
document.location.hash = '/productlist';
}
});
document
.getElementById('image-file')
.addEventListener('change', async (e) => {
const file = e.target.files[0];
const formData = new FormData();
formData.append('image', file);
showLoading();
const data = await uploadProductImage(formData);
hideLoading();
if (data.error) {
showMessage(data.error);
} else {
showMessage('Image uploaded successfully.');
document.getElementById('image').value = data.image;
}
});
},
render: async () => {
const request = parseRequestUrl();
Expand Down Expand Up @@ -63,6 +79,7 @@ const ProductEditScreen = {
<input type="text" name="image" value="${
product.image
}" id="image" />
<input type="file" name="image-file" id="image-file" />
</li>
<li>
<label for="brand">Brand</label>
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
"express": "^4.17.1",
"express-async-handler": "^1.1.4",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.9.21"
"mongoose": "^5.9.21",
"multer": "^1.4.2"
},
"devDependencies": {
"@babel/cli": "^7.10.3",
Expand Down
Empty file added uploads/file.txt
Empty file.