I'm trying to upload images with Vue Js, but it didn't work.
If you examine the codes below, you will see that I cannot transfer the file correctly. I couldn't find where the problem originated.
I am requesting your support.
// HTML code
// There is a problem in the image or file upload area to the card.
<input type="file" v-model="cardContent.cardContentImgPath" #change="onFileChange">
// Vuejs code
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
console.log(e.target.files);
if (!files.length)
return;
this.addToCardContent(files[0]);
},
addToCardContent: function(file){
let formData = app.toFormData(app.cardContent, file);
axios.post('https://example.com/note/api_card.php?action=addContent',formData, {
header:{
'Content-Type' : 'multipart/form-data'
}})
.then(function(response){
if(!response.data.error){
app.getListCardContent();
console.log(app.cardContent.cardContentImgPath);
app.cardContent = {cardContentText : '', cardContentImgPath : ''};
}
});
}
Related
I'm trying to use the Axios POST method to upload a file to Pinata IPFS:
FRONT-END:
<body>
<input type="file" id="file-upload" ></input>
<script> let file = document.getElementById("file-upload").value;</script>
</body>
FILE GETS SENT TO BACKEND THROUGH SOCKET.IO:
pin = (pinataApiKey, pinataSecretApiKey, file) => {
url = `https://api.pinata.cloud/pinning/pinFileToIPFS`;
const data = new FormData();
data.append("file", fs.createReadStream(`${file}`));
return axios.post(url, data, {
maxBodyLength: "Infinity",
headers: {
"Content-Type": `multipart/form-data; boundary=${data._boundary}`,
pinata_api_key: pinataApiKey,
pinata_secret_api_key: pinataSecretApiKey,
},
});
};
pin() only works when I use a local file path (i.e. C:/Users/anon/Desktop/project/untitled.png). If I try to use file.value (whose path is "C:\fakepath\testImage.jpeg"), the code doesn't work. I need the actual path of the uploaded file.
What do you get when you log file??
Perhaps you need to put this:
let file = document.getElementById("file-upload").value;
inside your js file:
And probably the best thing is to do some validations before the file is uploaded.
Im trying to share a file with Navigator.Share(), in android works perfect, but in ios don't work. I can share text but not images. Exist alternativees, or i cant share files in ios?
fetch(text)
.then(function(response) {
return response.blob()
})
.then(function(blob) {
var file = new File([blob], "image.png", {type: blob.type});
var filesArray = [file];
var shareData = { files: filesArray };
navigator.share({
url: 'https://cdn.shopify.com/s/files/1/0003/6270/9002/files/toshare-05.png?v=1621420555',
});
console.log("Your system doesn't support sharing files.");
});
}
}
I'm new in ReactJS and my backend is laravel and I have problem regarding inserting multiple files to the database, however if i use only the single upload (inserting one file to the database it's working for me.).
PROBLEM: regarding inserting multiple files in the database.
GOAL: To insert multiple files to the database
I have here
FORMDATA:
const formData = new FormData();
formData.append('myFile', this.state.image);
RESPONSE:
axios.post('/api/save_gallery_album_image', formData).then(response => {
console.log(response);
}).catch(error => (error.response));
OnChange:
handleChangeImage(e){
this.setState({
image:e.target.files[0]
})
// console.log(e.target.files);
}
JSX:
<label>Image</label>
<div className="custom-file">
<input type="file"
name="image"
multiple
onChange={this.handleChangeImage}
className="custom-file-input form-control"
accept="image/x-png,image/gif,image/jpeg"
id="file_selected"/>
<label className="custom-file-label" htmlFor="validatedCustomFile">Choose file...</label>
</div>
Server side Controller:
public function save_gallery_album_image(Request $request)
{
$multiple_gallery_file_upload = $request->file('myFile');
$titleValue = $request->get('titleValue');
$pageValue = $request->get('pageValue');
$now = new DateTime();
if($request->hasFile('myFile'))
{
foreach($multiple_gallery_file_upload as $myfiles)
{
$uniqueid=uniqid();
$original_name=$request->file('myFile')->getClientOriginalName();
$size=$request->file('myFile')->getSize();
$extension=$request->file('myFile')->getClientOriginalExtension();
$name=$uniqueid.'.'.$extension;
$path=$request->file('myFile')->storeAs('public',$name);
DB::insert('INSERT INTO album_category (cid,image,created_at) VALUES (?,?,?) ',[
$titleValue,
$name,
$now
]);
}
return response()->json('Input Saved');
}
}
I am facing the same problem I have fixed like this I hope it's helpful for you.
put this code on the right place and check it's working to upload multiple images Thanks.
<form>
<input name="product_image" type="file" multiple onChange={e => this.HandleProductImage(e)}/>
<button type="submit" onClick={e =>this.submitForm(e)}>
</form>
HandleProductImage = e => {
this.setState({
product_image: e.target.files
});
};
submitForm = e => {
const product = new FormData();
if (this.state.product_image) {
for (const file of this.state.product_image) {
product.append("image", file);
}
}
//then use your API to send form data
}
I guess you should request multiple time as files existed using loop.
When you request array of files in multipart form, the multipart form don't include all of your files. So you should send upload requests separately.
After check the comment, I added some sample code.
OnChange:
handleChangeImage(e) {
// Set file list
let files = e.target.files;
files.map((file) => {
// make diffent formData per each file and request.
let formData = new FormData();
formData.append('myFile', file);
axios.post('/api/save_gallery_album_image', formData)
.then(response => {
console.log(response);
}).catch(error => (error.response));
});
}
If you want to save multiple files in one request, I think you should also change your server-side codes.
For now, your server might save just one file per one request.
I am using Meteor and React JS. I also added Meteor Files.
https://github.com/VeliovGroup/Meteor-Files
By using this code,
this.Images = new FilesCollection({collectionName: 'Images'});
export default class Logo extends TrackerReact(React.Component){
constructor(){
...
Meteor.subscribe('files.images.all');
}
uploadLogo(e){
if (e.currentTarget.files && e.currentTarget.files[0]) {
// We upload only one file, in case
// there was multiple files selected
var file = e.currentTarget.files[0];
if (file) {
var uploadInstance = Images.insert({
file: file,
streams: 'dynamic',
chunkSize: 'dynamic',
transport: 'http'
}, false);
uploadInstance.on('start', function() {
//template.currentUpload.set(this);
});
uploadInstance.on('end', function(error, fileObj) {
if (error) {
alert('Error during upload: ' + error.reason);
} else {
console.log("done");
alert('File "' + fileObj.name + '" successfully uploaded');
}
});
uploadInstance.start();
}
}else{
console.log("error");
}
}
render(){
...
<input type="file" id="fileinput" onChange={this.uploadLogo.bind(this)} />
}
I am able to upload the file but I don't see any files in my directory.
Here is my publish.js,
this.Images = new Meteor.Files({
debug: true,
collectionName: 'Images',
allowClientCode: false, // Disallow remove files from Client
onBeforeUpload: function (file) {
// Allow upload files under 10MB, and only in png/jpg/jpeg formats
if (file.size <= 1024*1024*10 && /png|jpg|jpeg/i.test(file.extension)) {
return true;
} else {
return 'Please upload image, with size equal or less than 10MB';
}
}
});
Meteor.publish('files.images.all', function () {
return Images.find().cursor;
});
How can I display the image? How can I limit the user to upload files that are only images?
For me, their API Docs is not rich. I can't understand what the things they are talking in their docs.
By default uploaded files are stored in the file system. Read the FAQ:
Where are files stored by default?: by default if config.storagePath
isn't passed into Constructor it's equals to assets/app/uploads and
relative to running script:
On development stage:
yourDevAppDir/.meteor/local/build/programs/server
Note: All files
will be removed as soon as your application rebuilds or you run meteor
reset. To keep your storage persistent during development use an
absolute path outside of your project folder, e.g. /data directory.
On production: yourProdAppDir/programs/server
So you need to set a location with config.storagePath
Am working on a web application and we allow users to upload files to our server. Am trying to do client side compression before uploading files to the server. What would be the better way to achieve this using HTML5 and JavaScript.
Thanks.
The common mechanism to do what you want is using FileReader and a JavaScript client-side compression library (i.e. compressjs).
In 2022 it's almost too simple, if the browser supports CompressionStream, FormData and Response.
In the example below I use FormData to collect all the fields from the form.
Then I use the readable stream from the file, and pipe it though the compression stream. Then I use Response to read everything from the compressed stream and return it in a blob.
async function compress(file, encoding = 'gzip') {
try {
return {
data: await new Response(file.stream().pipeThrough(new CompressionStream(encoding)), {
headers: {
'Content-Type': file.type
},
}).blob(),
encoding,
};
} catch (error) {
// If error, return the file uncompressed
console.error(error.message);
return {
data: file,
encoding: null
};
}
}
theForm.addEventListener(
'submit',
(event) => event.preventDefault()
)
theForm.addEventListener(
'input',
async function(event) {
// collect all fields
const fd = new FormData(theForm);
// Get 'file handle' from imput elemen
const file = fd.get('theFile');
if (!file) return
const encoding = fd.get('theEncoding');
const compressed = await compress(file, encoding);
theMessage.value = [
'Compressed with', compressed.encoding,
'Source file was', file.size, 'bytes',
'and the compressed file', compressed.data.size,
'saving', ((1 - compressed.data.size / file.size) * 100)
.toFixed(0),
'%.'
].join(' ')
}
)
form>* {
display: block;
width: 100%;
}
<form id="theForm">
<select name="theEncoding">
<option>gzip</option>
<option>deflate</option>
<option>deflate-raw</option>
</select>
<input type="file" name="theFile" id="theFile">
</form>
<output id="theMessage"></output>