So I have 2 project files, 1 for the homepage where users can submit data such as text and images, and the other one is for the admin pages, to read the submitted data from users, both project uses the same database.
The datas have been successfully stored and displayed in both projects, the problem is for the images, It's only showing the image path, not the image itself like this
enter image description here
I tried to copy the image from the homepage to the adminpage but still it's just showing the image path only.
What could be the problem ? because In the homepage, If the user submit an image, The image will be uploaded to images/imgupload folder, and the data that will be sent to the database is like this :
images/imgupload/4cad6hMcc36c1dtGw6K1OUkRnAFCucEpDP44vN9B.jpg
Is it the right way to store image to a database? because then in the admin page, It will be only showing the path, not the image itself.
This is the methods in the homepage
methods: {
async submitForm() {
const formData = new FormData();
formData.append('text', this.form.text);
formData.append('file', this.form.file);
try {
const response = await axios.post('/api/endpoint', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log(response.data);
} catch (error) {
console.error(error);
}
},
uploadFile() {
this.form.file = this.$refs.fileInput.files[0];
},
},
The controller
public function store(Request $request)
{
$request->validate([
'text' => 'required',
'file' => 'required|file',
]);
$formData = new FormData();
$formData->text = $request->text;
$formData->file = $request->file('file')->store('formdatas');
$formData->save();
return response()->json(['success' => 'Form data was saved successfully.']);
}
The routes :
Route::post('/endpoint', function (Request $request) {
$text = $request->input('text');
$file = $request->file('file');
$data = new FormData();
$data->text = $text;
$data->file = $file->store('images/imgupload');
$data->save();
return response()->json(['message' => 'Success']);
});
Related
I am using Local Storage for my login page
but my variables not storing in the local storage I don't know why....
I am using the following code on my button click....
But the APi i am using is correct... It works fine
res.data.status gives true or false,Inside Axios .then => If is used for correct username and password and else is used for incorrct user
This is my Code:
async function handleSubmit(e) {
var url = 'http://localhost/project/login.php?name='+name+"&price="+price;
const formData = new FormData();
formData.append('avatar',"hi")
await axios.post(url, formData)
.then(res => {
if(!res.data.status){
localStorage.setItem('username', name);
alert(res.data.message);
}else{
alert(res.data.message);
}
})
}
if your variable is not stored in the localStorage. that's because of the condition you have. also as you're sure that your API is working fine and you can successfully make a request and receive a response. then the issue is with the condition. because from your code. you're making conditions only if the request is not successful. you don't have the condition for success.
async function handleSubmit(e) {
var url = 'http://localhost/project/login.php?name='+name+"&price="+price;
const formData = new FormData();
formData.append('avatar',"hi")
await axios.post(url, formData)
.then(res => {
if(!res.data.status){ <= remove the !
localStorage.setItem('username', name);
alert(res.data.message);
}else{
alert(res.data.message);
}
})
}
I have a react frontend app with nodejs/express and typeorm/mysql on the backend. I have built a clone of twitter's "news feed" where we can post a new tweet(article). At the top, I have an input field where user can submit new post. Once the user submits new post, he has to refresh the page in order to be able to see new post. How can I achieve 'live reload' without reloading the app or seeing the new post once it is submitted. I am using useEffect() hook and fetch to send HTTP requests to communicate with backend.
Code for fetching posts and creating new one from the homepage:
const [posts, setPosts] = React.useState([]);
const [isLoaded, setIsLoaded] = React.useState(false);
const [error, setError] = React.useState(null);
const [post, setNewPost] = React.useState("");
React.useEffect(() => {
fetch(`${serverUrl()}/posts`)
.then((res) => res.json())
.then(
(posts) => {
setIsLoaded(true);
setPosts(posts);
},
(error) => {
setIsLoaded(true);
setError(error);
}
);
}, []);
const createNewPost = async (postData) => {
return fetch(`${serverUrl()}/posts`, {
method: "POST",
// add new
headers: { "Content-type": "application/json", userid: token },
body: JSON.stringify(postData),
}).then((data) => {
return data.json();
});
};
const handleSubmit = async (e) => {
e.preventDefault();
await createNewPost({ title: "Lorem ipsum", body: post });
setNewPost("");
};
In the createNewPost method, after the post has been added successfully, you must push the new post to your state.
const createNewPost = async (postData) => {
return fetch(`${serverUrl()}/posts`, {
method: "POST",
// add new
headers: { "Content-type": "application/json", userid: token },
body: JSON.stringify(postData),
}).then((data) => {
// success!
setPosts([...posts, postData]);
return data.json();
});
};
But of course, postData must match the schema of a single post inside your posts array for this to work.
The best solution for this is, to have the backend return the new post as JSON object, and then update the posts array.
A simple workaround would be that you could just manipulate the state of your "posts" variable.
In your createNewPost, if the promise returns in success without any errors or exceptions, i.e. enters into "then" block, you can append your new post -> {title: "new post", body: post} to the already fetched "posts" variable. This way state will be updated and you will see the new post.
i.e.
let prevPosts = [...posts];
prevPosts.push(newPost);
setPosts(prevPosts); // Append at last. You can even push at first index, that way post will appear at top.
So even if you refresh, the new posts will be loaded, as you already did a create query at backend while submitting the post and later updated the post variable.
I have an API request that returns the image of the product that had been saved in the database in the form of buffer in MONGODB. The API returns the image and I want this image as source to my html element. How do I do that?
The API request is:
router.get('/product/avatar/:id', async (req, res) => {
try{
const product = await Product.findById(req.params.id)
if(!product || !product.avatar){
throw new Error()
}
// console.log('product avatar')
res.set('Content-Type', 'image/png')
res.send(product.avatar)
} catch(e) {
res.status(404).send()
}
})
And this is how I was trying to assign that image to my HTML
the code snippet given below is a part of the javascript used to render information on webpage from database.
var picId = data[i].name + 'Image'
// console.log(data[i]._id)
fetch('/product/avatar/'+data[i]._id, {
method: 'GET'
}).then((res) => {
return res.json()
}).then((data) => {
// picId.value = data
// document.getElementById(picId).src = data
console.log(data)
})
I have a collection of Contacts inside my MongoDB
Those Contacts have avatars (or "profile pictures")
Here is the profile picture for the above user:
... and a chunk of that file (there's only one).
I'm trying to take ^^^ that ^^^ chunk and parse it into a base-64 data URL in order to return it from my server back to my application and use it inside an <img>'s src attribute.
app.get('/queryContacts', (req, res) => {
const getContacts = async query => {
let contacts = await db
.collection('contacts')
.find(query)
.toArray();
return contacts;
};
const getImages = async id => {
let imageUrl = 'data:image/jpg;base64';
await bucket
.openDownloadStream(new ObjectID(id))
.on('data', chunk => {
imageUrl += chunk.toString('base64');
})
.on('end', () => {
return imageUrl;
});
}
getContacts({account_id: new ObjectID(req.query.id)}).then(contacts => {
Object.keys(contacts).forEach(key => {
getImages(contacts[key].image_id).then(url => {
console.log(url); // undefined
contacts[key].imageUrl = url;
});
});
res.json(contacts);
});
});
The problem is that when I try this, the URL is undefined because getImages() isn't waiting for the 'end' event to finish.
I am making a django-angularjs webapp.
There is a option for file uploading for the users.
I want to provide users with some sample images to upload.
So it will be like the sample images will be sent by server to client and again send back to the server if the client chooses them as Fresh upload.
angularjs directive:
angular.module('users').directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
my html:
<input type="file" file-model="myFile"/><br><br>
<button ng-click="uploadFile()">Upload</button>
angular-js controller:
$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "/multer";
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl,fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
console.log("success!!");
})
.error(function(){
console.log("error!!");
});
};
Using the code above the user can select the image from their pc and upload them.
Now if we have the url for the sample images sent by server.
How to code the angular controller to get images for their file object from those urls?
like $scope.myFile=getImageFileObjectFromUrl(url) ??
thanks for help
$http.get("image_url", {responseType: "arraybuffer"}).success((data) => {
fd.append('file', data);
});
It's a general idea, when you get your image url, just make a request as arraybuffer to the URL, then you just have to pass the blob object to your formdata.
Convert a image from the given url into a file object:
$http.get(url,{responseType: "blob"}).success((data) => {
var file = new File([data], "sample.jpg");
$scope.sampleFile=file;
});
It also may help
$http.get(url.path, {responseType: "blob"}).then((res) => {
let fileUrl = (window.URL || window.webkitURL).createObjectURL(res.data);
resolve({file: fileUrl, type: url.type, name: url.name});
});