I have an app that uses October CMS to store images in a database. When I add the image in October, I use the following method:
Which gives me the image_path in October:
public $attachOne = [
'image' => ['System\Models\File']
];
public function getImagePathAttribute(){
return $this->image->path;
}
http://localhost/bit703/module6/storage/app/uploads/public/60b/6cb/8d3/60b6cb8d39915448328696.jpg
The problem I'm having is that when I upload my image from Vue, it's storing it without the path of where the image is being stored, causing errors in the October backend.
Is there a way to find that image path and add it to my request in Vue? My Vue code looks as follows:
<script>
import axios from 'axios';
export default {
data() {
return {
apiRequest: new this.$request({
name: '',
description: '',
tags: '',
filter: '',
file: '',
response: '',
image_path: '',
}),
errorMessage: '',
successMessage: '',
submitted: false,
};
},
methods: {
onSubmit() {
const bodyFormData = new FormData();
bodyFormData.append('name', 'iamge1');
bodyFormData.append('description', 'An image');
bodyFormData.append('tags', 'Winter');
bodyFormData.append('filter', '1977');
bodyFormData.append('user_id', 2);
bodyFormData.append('file', this.file);
bodyFormData.append('image_path', '???');
this.onFileChange();
axios({
method: 'post',
url: 'http://localhost/bit703/module6/api/v1/images',
data: bodyFormData,
headers: { 'Content-Type': 'multipart/form-data' },
})
.then((response) => {
this.resposne = response;
});
},
onFileChange(e) {
const image = e.target.files[0];
this.file = image;
},
},
};
</script>
Related
This question already has an answer here:
how to send post a file and a body with axios in javascript?
(1 answer)
Closed 9 months ago.
(front vuejs3 + axios | back nodejs + prisma sql)
I have a function to create a post. When I use it with postman it works.
But when I use it with frontend it returns me a formdata = null
On this.selectedFile, i have the file
can you help me please ?
data () {
return {
title: '',
content: '',
userId: '',
selectdFile: null,
}
},
methods: {
onFileSelected (event) {
this.selectedFile = event.target.files[0];
console.log(this.selectedFile);
},
async createPost() {
const formData = new FormData();
formData.append( 'image', this.selectedFile, this.selectedFile.name );
console.log('ok')
console.log(formData);
const id = localStorage.getItem('userId');
const response = await axios.post('http://localhost:3000/api/post', {
title: this.title,
content: this.content,
userId: parseInt(id),
attachment: formData,
}, {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
},
});
console.log(response);
},
Voici le resultat :
Try this:
const response = await axios.postForm(
"http://localhost:3000/api/post",
{
title: this.title,
content: this.content,
userId: parseInt(id),
attachment: this.selectedFile,
},
{
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
}
);
I have a postAsset action in my vuex store like so
async postAsset({dispatch}, asset) {
const f = await dispatch('srcToFile', asset);
asset[0].files.fileList = f;
const fileData = asset[0].files.fileList;
const detailData = asset[0].detail;
const fData = new FormData();
fData.append('Name', asset[0].name);
Object.keys(detailData).forEach((key) => {
fData.append(`Detail.${key}`, detailData[key]);
});
for (var i = 0; i < fileData.length; i++) {
fData.append('Files', fileData[i]);
}
await axios({
method: 'post',
url: 'https://localhost:5001/api/Assets',
data: fData,
headers: {
'Content-Type': undefined
}
})
.then(function(response) {
console.warn(response);
})
.catch(function(response) {
console.warn(response);
});
}
It is successfully posting to my api backend and to the database.
The issue that I am running into is that after I make the first post it posts the previous data and the new data I do not know why it is doing this. I did add await to the axios call but that just slowed it down it is still posting two times after the first and im sure if i keep posting it will continue to post the previous ones into the db again and again. Im at a loss as to what is going on so reaching out for some assistance to see if I can get this resolved.
examples of what it looks like in the db
does anyone have any advice for me so I can get this fixed? I should only be getting one item posted at a time that is the desired result. I have gone through my inputs and put in .prevent to stop them from clicking twice but I don't think it is that .. this is like it is saving the data and reposting it all at once each time I add a new record .
UPDATE:
the code that calls the action
populateAssets ({ dispatch }, asset) {
return new Promise((resolve) => {
assets.forEach((asset) => {
commit('createAsset', asset);
);
dispatch('postAsset', asset);
resolve(true);
});
},
the populate assets populates a list with a completed asset.
and asset is coming from the srcToFile method
that converts the files to a blob that I can post with
async srcToFile(context, asset) {
const files = asset[0].files.fileList;
let pmsArray = [];
for (let f = 0; f < files.length; f++) {
var data = files[f].data;
let name = files[f].name;
let mimeType = files[f].type;
await fetch(data)
.then(function(res) {
const r = res.arrayBuffer();
console.warn('resource ', r);
return r;
})
.then(function(buf) {
console.warn('buffer: ', [buf]);
let file = new File([buf], name, { type: mimeType });
pmsArray.push(file);
});
}
console.warn(pmsArray);
return pmsArray;
},
asset is an array from my add asset component
structure of asset
name: '',
detail: {
category: '',
manufacturer: '',
model: '',
serialNumber: '',
purchasePlace: '',
quantity: 1,
acquiredDate: '',
purchasePrice: '',
currentValue: '',
condition: '',
assetLocation: '',
retiredDate: '',
description: ''
},
files: {
fileList: []
}
hope this helps out some
the whole store file
import Vue from 'vue'
import Vuex from 'vuex'
import { states } from '../components/enums/enums'
import { getField, updateField } from 'vuex-map-fields'
import axios from 'axios'
Vue.use(Vuex);
const inventory = {
namespaced: true,
strict: true,
state: {
assets: {
items: []
},
categories: [],
manufacturers: [],
assetLocations: [],
conditions: ['New', 'Fair', 'Good', 'Poor']
},
getters: {
assetItems: state => state.assets.items,
getAssetById: (state) => (id) => {
return state.assets.items.find(i => i.id === id);
},
conditions: (state) => state.conditions,
categories: (state) => state.categories,
manufacturers: (state) => state.manufacturers,
assetLocations: (state) => state.assetLocations
},
mutations: {
createAsset (state, assets) {
state.assets.items.push(assets);
},
createCategories (state, category) {
state.categories.push(category);
},
createManufacturers (state, manufacturer) {
state.manufacturers.push(manufacturer);
},
createLocations (state, locations) {
state.assetLocations.push(locations);
}
},
actions: {
addToCategories ({ commit }, categories) {
commit('createCategories', categories);
},
addToManufacturers ({ commit }, manufacturers) {
commit('createManufacturers', manufacturers);
},
addToLocations ({ commit }, locations) {
commit('createLocations', locations);
},
populateAssets ({ dispatch }, asset) {
//return new Promise((resolve) => {
// assets.forEach((asset) => {
// commit('createAsset', asset);
// });
dispatch('postAsset', asset);
// resolve(true);
//});
},
addAsset ({ dispatch, /*getters*/ }, newAsset) {
//let assetCount = getters.assetItems.length;
//newAsset.id = assetCount === 0
// ? 1
// : assetCount++;
dispatch('populateAssets', [newAsset]);
},
async srcToFile(context, asset) {
const files = asset[0].files.fileList;
let pmsArray = [];
for (let f = 0; f < files.length; f++) {
var data = files[f].data;
let name = files[f].name;
let mimeType = files[f].type;
await fetch(data)
.then(function(res) {
const r = res.arrayBuffer();
console.warn('resource ', r);
return r;
})
.then(function(buf) {
console.warn('buffer: ', [buf]);
let file = new File([buf], name, { type: mimeType });
pmsArray.push(file);
});
}
console.warn(pmsArray);
return pmsArray;
},
async postAsset({ dispatch }, asset) {
const f = await dispatch('srcToFile', asset);
asset[0].files.fileList = f;
const fileData = asset[0].files.fileList;
const detailData = asset[0].detail;
const fData = new FormData();
fData.append('Name', asset[0].name);
Object.keys(detailData).forEach((key) => {
fData.append(`Detail.${key}`, detailData[key]);
});
for (var i = 0; i < fileData.length; i++) {
fData.append('Files', fileData[i]);
}
await axios({
method: 'post',
url: 'https://localhost:5001/api/Assets',
data: fData,
headers: { 'Content-Type': undefined }
})
.then(function(response) {
console.warn(response);
})
.catch(function(response) {
console.warn(response);
});
}
}
};
const maintenance = {
state: {
backup: []
},
strict: true,
getters: {},
mutations: {},
actions: {}
};
const assetProcessing = {
namespaced: true,
state: {
currentAsset: {
id: 0,
name: '',
detail: {
category: '',
manufacturer: '',
model: '',
serialNumber: '',
purchasePlace: '',
quantity: 1,
acquiredDate: '',
purchasePrice: '',
currentValue: '',
condition: '',
assetLocation: '',
retiredDate: '',
description: ''
},
files: {
fileList: []
}
},
filePosition: -1,
selectedItem: -1,
state: states.view,
isNewAsset: false
},
getters: {
getField,
getOpenAsset (state) {
return state.currentAsset
},
getSelectedAsset: (state, getters, rootState, rootGetters) => (id) => {
if (state.isNewAsset) return state.currentAsset
Object.assign(state.currentAsset, JSON.parse(JSON.stringify(rootGetters['inventory/getAssetById'](!id ? 0 : id))));
return state.currentAsset
},
appState: (state) => state.state,
getCurrentPosition (state) {
return state.filePosition
},
selectedAssetId: (state) => state.selectedItem
},
mutations: {
updateField,
setAsset (state, asset) {
Object.assign(state.currentAsset, asset)
},
setFiles (state, files) {
Object.assign(state.currentAsset.files, files)
},
newAsset (state) {
Object.assign(state.isNewAsset, true)
Object.assign(state.currentAsset, {
id: 0,
name: '',
detail: {
category: '',
manufacturer: '',
model: '',
serialNumber: '',
purchasePlace: '',
quantity: 1,
acquiredDate: '',
purchasePrice: '',
currentValue: '',
condition: '',
assetLocation: '',
retiredDate: '',
description: ''
},
files: {
fileList: []
}
})
},
updateSelectedItem (state, id) {
Vue.set(state, 'selectedItem', id);
},
updateState (state, newState) {
Vue.set(state, 'state', newState);
}
},
actions: {}
};
export const store = new Vuex.Store({
modules: {
inventory: inventory,
maintenance: maintenance,
assetProcessing
}
})
add asset is called when the user clicks the save button on the form
addAsset () {
this.$store.dispatch('inventory/addAsset', this.newAsset) <--- this calls add asset
this.$store.commit('assetProcessing/updateState', states.view);<-- this closes the window
},
So after much debugging we found that the eventbus was firing multiple times causing the excessive posting we added
beforeDestroy() {
eventBus.$off('passAssetToBeSaved');
eventBus.$off('updateAddActionBar');
},
to the AssetAdd.vue component and it eliminated the excessive posting of the asset.
I want to thank #phil for helping me out in this.
I am using vue-tables-2 for manage data. I wanna implement server side. But I got a problem. I can get the data as well. But I dont know why I got that error message. This is my code:
HTML
<v-server-table :columns="columns" :options="options"></v-server-table>
Vue Js
<script>
var config = {
"PMI-API-KEY": "erpepsimprpimaiy"
};
export default {
name: "user-profile",
data() {
return {
columns: ["golongan_name"],
options: {
requestFunction: function(data) {
return this.$http({
url: "api/v1/golongan_darah/get_all_data",
method: "post",
headers: config
}).then(res => {
this.data = res.data.data;
console.log(res);
});
},
filterable: ["golongan_name"],
sortable: ["golongan_name"],
filterByColumn: true,
perPage: 3,
pagination: { chunk: 10, dropdown: false },
responseAdapter: function(resp) {
return {
data: resp.data,
count: resp.total
};
}
}
};
}
};
</script>
This is the error:
enter image description here
I'm using expo camera to take a picture. The output I get is a file in format file:///data/user/0/host.exp.exponent/..../Camera/1075d7ef-f88b-4252-ad64-e73238599e94.jpg
I send this file path to the following action and try to upload it to
export const uploadUserPhoto = (localUri,uid) => async dispatch => {
let formData = new FormData();
formData.append('avatar', { uri: localUri, fileName: uid});
let res = await fetch(`${API_URL}api/uploadPhoto`, {
method: 'POST',
body: formData,
header: {
'content-type': 'multipart/form-data',
},
});
Afterward, I get [Unhandled promise rejection: TypeError: Network request failed] and nothing arrives to server. I tried using some string to send in the body and the fetch worked, so I guess it has something to do with my formData configuration.
The formData is:
{
"_parts": Array [
Array [
"avatar",
Object {
"fileName": "6eAntcmoEsdBeSD2zfka9Nx9UHJ3",
"type": "jpg",
"uri": "file:///data/us....2e6e3e8d3223.jpg",
},
],
],
}
How I use postman to test my sails controller
Sails controller function:
uploadPhoto: function (req, res) {
req.file('avatar').upload({
adapter: require('skipper-s3'),
key: 'XXXX',
secret: 'XXX',
bucket: 'XXX',
saveAs: req.param('fileName') + '.png',
}, function (err, filesUploaded) {
....
});
});
}
Problem was that I didn't specify the filename.
Just did this and it worked!!! :)
data.append('filename', 'avatar');
data.append('fileName', uid);
data.append('avatar', {
uri: photo.uri,
name: 'selfie.jpg',
type: 'image/jpg'
});
const config = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data
};
fetch(`${API_URL}api/uploadPhoto`, config).then(responseData => {
console.log(responseData);
}).catch(err => { console.log(err); });
just add these params in photo this worked for me
data.append('avatar', {
uri: photo.uri,
name: 'selfie.jpg',
type: 'image/jpg'
});
I am currently uploading videos and images using base64 encoding but it was highly recommended to use an alternative to this. I am using RNFetchBlob to read the encoded file and then attach it to SuperAgent for uploading. I have seen some examples of using FormData to attach the file but cannot find a complete working example. If someone could provide a code example on how to achieve this I would greatly appreciate it.
RNFetchBlob.fs.readFile(filePath, 'base64')
.then((base64data) => {
let base64Image = `data:video/mp4;base64,${base64data}`;
let uploadRequest = superagent.post(uploadURL)
uploadRequest.attach('file',base64Image)
Object.keys(params).forEach((key) => {
uploadRequest.field(key,params[key])
})
uploadRequest.on('progress', function(e) {
this.props.setVideoUploadProgress(e.percent)
}.bind(this))
uploadRequest.end((err,resp) => {
})
})
I am using react-native-image-picker to allow users to select or record a video, which gives me a URI of the video file path. Then I use RNFetchBlob to upload it to the server.
RNFetchBlob.fetch('POST', 'Upload API endpoint', {
...this.getHeader(),
'Content-Type': 'multipart/form-data'
// Change BASE64 encoded data to a file path with prefix `RNFetchBlob-file://`.
// Or simply wrap the file path with RNFetchBlob.wrap().
}, [
// element with property `filename` will be transformed into `file` in form data
{ name: 'file', filename: 'video.mp4', data: RNFetchBlob.wrap(this.state.videoUri) },
// custom content type
]).uploadProgress({ interval: 250 }, (written, total) => {
let uploaded = (written / total) * 100
this.setState({
uploadProgress: uploaded.toFixed(1)
})
})
.then((response) => {
if (response.ok) {
this.setState({
uploading: false,
uploadSuccess: true,
uploadFailed: false,
})
}
}).catch((err) => {
this.setState({
uploading: false,
uploadSuccess: false,
uploadFailed: true,
})
})
Basically you have to give the path of your image, audio or video to fetch blob. The following code worked for me:
RNFetchBlob.fetch(
'POST',
`${BASE_URL}vehicle/vehicleRegistration`,
{
Authorization: 'Bearer ' + authToken,
'Content-Type': 'multipart/form-data,octet-stream',
},
[
{
name: 'photo',
filename: 'vid.mp4',
data: RNFetchBlob.wrap(vehicleImage.uri),
},
{
name: 'email',
data: user.email,
},
{
name: 'userId',
data: user.id,
},
{
name: 'vehicleType',
data: values.vehicleType,
},
{
name: 'make',
data: values.make,
},
{
name: 'buildYear',
data: values.buildYear,
},
{
name: 'model',
data: values.model,
},
{
name: 'nickName',
data: values.nickName,
},
{
name: 'engineSize',
data: values.engineSize,
},
],
)
.uploadProgress((written, total) => {
console.log('uploaded', written / total);
})
.then(response => response.json())
.then(RetrivedData => {
console.log('---retrieved data------', RetrivedData);
Toast.show({
text1: 'Success',
text2: 'Vehicle Added to Garage!',
type: 'success',
});
})
.catch(err => {
console.log('----Error in adding a comment----', err);
Toast.show({
text1: 'Request Failed',
text2: err?.response?.data?.message,
type: 'error',
});
});