i am having trouble here, it is that when i click on the anchor tag the file is downloaded but when i open it.it always says file type not supported.
here is the react and backend codes respectively.
react
import { useState, useEffect, useContext } from "react";
import axios from "axios";
import { UserContext } from "../App.jsx";
import { useLocation, useOutletContext } from "react-router-dom";
function Class() {
const location = useLocation();
const [showForm, setShowForm] = useState(false);
const [link, setLink] = useState({url: '',filename:'',description: ''});
const [selected, setSelected] = useState(null);
const [data, setData] = useState([]);
const { state, dispatch } = useContext(UserContext);
const { setMsg } = useOutletContext();
useEffect(() => {
axios
.post("http://localhost:5000/user/subjects/find", {
fullName: state.name,
})
.then((res) => {
setData(res.data.subjects);
})
.catch((err) => console.log(err));
setMsg(location.state?.msg);
}, []);
function handleClick(i) {
setShowForm(true);
setSelected(i);
axios
.post("http://localhost:5000/user/find/upload", {
fullName: state.name, subject: data[i]
})
.then((res) => {
const fileData = res.data.fileData;
const description = res.data.description;
const filename = res.data.filename;
console.log(filename,description);
// Create a blob URL for the file data
const blob = new Blob([fileData], { type: "application/octet-stream" });
const url = URL.createObjectURL(blob);
const newObj = {...link};
newObj.url = url;
newObj.filename = filename;
newObj.description = description;
setLink(newObj);
// Create a link to download the file
// const link = document.createElement("a");
// link.href = url;
// link.download = data[i]; // Assuming the file name is the same as the subject
// document.body.appendChild(link);
// link.click();
// document.body.removeChild(link);
// Handle the description
console.log(description);
})
.catch((err) => console.log(err));
}
return (
<div className="w-full flex justify-evenly">
{data.map((sub, i) => {
return (
<button type="submit"
className={`text-white ${i === selected?`bg-green-600`:`bg-blue-600`} border h-10 w-1/3 py-2 rounded-md`}
onClick={(e) => handleClick(i)} key={i}>
{sub}
</button>
);
})}
{link.url &&
<div>
<div>{link.description}</div>
<a download={`${link.filename}`} href={link.url}>{link.filename}</a>
</div>}
</div>
);
}
export default Class;
backend
router.route("/class/upload").post(upload.single("file"), async (req, res) => {
try {
const {
batch,
department,
stream,
fullName,
classId,
subject,
description,
} = req.body;
const teacher = await User.findOne({ fullName });
const teacherId = teacher._id;
console.log({ file: req.file, teacher, classId });
const file = new File({
batch,
department,
stream,
classId,
teacherId,
subject,
description,
filename: req.file.filename,
path: req.file.path,
});
await file.save();
res.json({ success: true });
} catch (error) {
console.error(error);
res.status(500).json({ success: false, error: "Unable to upload file" });
}
});
router.post("/find/upload", async (req, res) => {
try {
const { fullName, subject } = req.body;
const user = await User.findOne({ fullName });
const findSem = await Class.find({
batch: user.batch,
department: user.department,
stream: user.stream,
students: user._id,
});
if (findSem.length === 1) {
semester = 1;
} else if (findSem.length === 2) {
semester = 2;
}
const findClass = await Class.findOne({
batch: user.batch,
department: user.department,
stream: user.stream,
students: user._id,
semester,
});
const arr = findClass.teacher[semester];
const filtarr = arr.filter((a) => a.subject.includes(subject));
console.log(filtarr);
const file = await File.findOne({
batch: user.batch,
department: user.department,
stream: user.stream,
teacherId: filtarr[0]?.teacherId,
classId: findClass._id,
subject,
});
const filePath = path.join(__dirname, "uploads", file.filename);
fs.readFile(filePath, (err, data) => {
if (err) throw err;
const contentType = file.contentType || "application/octet-stream";
res.set("Content-Type", contentType);
const description = file.description;
const filename = file.filename;
res.json({ success: true, fileData: data, description, filename });
});
} catch (error) {
console.error(error);
res
.status(500)
.json({ success: false, error: "Unable to share the file and its " });
}
});