How do I pin a location on laravel backpack - laravel-backpack

I want to pin a location when user enter his address information in laravel backpack?
this is Address field in controller
'name' => 'address-input',
'type' => 'customGoogleMaps',
'label' => "Google Maps",
'hint' => 'Help text',
'attributes' => [
'class' => 'form-control map-input',
],
'view_namespace' => 'custom-google-maps-field-for-backpack::fields',
This is customGoogleMaps field (customGoogleMaps.blade.php)
<div #include('crud::inc.field_wrapper_attributes')>
<label>{!! $field['label'] !!}</label>
<input type="text" id="{{ $field['name'] }}" name="{{ $field['name'] }}"
value="{{ old($field['name']) ? old($field['name']) : (isset($field['value']) ? $field['value'] : (isset($field['default']) ? $field['default'] : '' )) }}"
#include('crud::inc.field_attributes')>
<input type="hidden" name="address_latitude" id="address-latitude" value="0" />
<input type="hidden" name="address_longitude" id="address-longitude" value="0" />
<div id="address-map-container" style="width:100%;height:400px; ">
<div style="width: 100%; height: 100%" id="address-map"></div>
</div>
{{-- HINT --}}
#if (isset($field['hint']))
<p class="help-block">{!! $field['hint'] !!}</p>
#endif
</div>
#if ($crud->checkIfFieldIsFirstOfItsType($field, $fields))
{{-- FIELD EXTRA CSS --}}
{{-- push things in the after_styles section --}}
#push('crud_fields_styles')
<!-- no styles -->
#endpush
{{-- FIELD EXTRA JS --}}
{{-- push things in the after_scripts section --}}
#push('crud_fields_scripts')
<!-- no scripts -->
<script
src="https://maps.googleapis.com/maps/api/js?key={{ env('GOOGLE_MAPS_API_KEY') }}&libraries=places&callback=initialize" async defer></script>
<script>
function initialize() {
$('form').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
});
const locationInputs = document.getElementsByClassName("map-input");
const autocompletes = [];
const geocoder = new google.maps.Geocoder;
for (let i = 0; i < locationInputs.length; i++) {
const input = locationInputs[i];
const fieldKey = input.id.replace("-input", "");
const isEdit = document.getElementById(fieldKey + "-latitude").value != '' && document.getElementById(fieldKey + "-longitude").value != '';
const latitude = parseFloat(document.getElementById(fieldKey + "-latitude").value) || -33.8688;
const longitude = parseFloat(document.getElementById(fieldKey + "-longitude").value) || 151.2195;
const map = new google.maps.Map(document.getElementById(fieldKey + '-map'), {
center: {lat: latitude, lng: longitude},
zoom: 13
});
const marker = new google.maps.Marker({
map: map,
position: {lat: latitude, lng: longitude},
});
marker.setVisible(isEdit);
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.key = fieldKey;
autocompletes.push({input: input, map: map, marker: marker, autocomplete: autocomplete});
}
for (let i = 0; i < autocompletes.length; i++) {
const input = autocompletes[i].input;
const autocomplete = autocompletes[i].autocomplete;
const map = autocompletes[i].map;
const marker = autocompletes[i].marker;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
marker.setVisible(false);
const place = autocomplete.getPlace();
geocoder.geocode({'placeId': place.place_id}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
const lat = results[0].geometry.location.lat();
const lng = results[0].geometry.location.lng();
setLocationCoordinates(autocomplete.key, lat, lng);
}
});
if (!place.geometry) {
window.alert("No details available for input: '" + place.name + "'");
input.value = "";
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
});
}
}
function setLocationCoordinates(key, lat, lng) {
const latitudeField = document.getElementById(key + "-" + "latitude");
const longitudeField = document.getElementById(key + "-" + "longitude");
latitudeField.value = lat;
longitudeField.value = lng;
}
</script>
#endpush
#endif
It display the following Error:
InvalidArgumentException View [inc.field_wrapper_attributes] not found. (View:
C:\xampp\htdocs\CRM\vendor\abr4xas\gmaps-input-backpack\src\resources\views\fields\customGoogleMaps.blade.php)

Related

I want to use "el-upload" to upload images and documents, but I want to display the images

I want to use "el-upload" to upload images and documents, but I want to display the images. If "list-type='picture-card'" is used, the document will also be shown with an incorrect cover. So is there any way I can upload files that show images thumbnails, documents that show names?
enter image description here
<el-upload
action=""
ref="upload"
:auto-upload="false"
:on-change="onchange">
<el-button slot="trigger" size="small" type="primary">Click to Upload</el-button>
</el-upload>
<el-image
style="width: 100px; height: 100px"
:src="fileList[0]"
:preview-src-list="fileList">
</el-image>
data() {
return {
fileList: []
}
}, methods: {
onchange(file, fileList){
this.fileList.push(URL.createObjectURL(file.raw))
}
}
<template>
<div class="upload-file">
<el-upload
multiple
:action="uploadFileUrl"
:before-upload="handleBeforeUpload"
:file-list="fileList"
:limit="limit"
:on-error="handleUploadError"
:on-exceed="handleExceed"
:on-success="handleUploadSuccess"
:show-file-list="false"
:headers="headers"
class="upload-file-uploader"
ref="upload"
>
<!-- 上传按钮 -->
<el-button type="primary">选取文件</el-button>
</el-upload>
<!-- 上传提示 -->
<!-- <div class="el-upload__tip" v-if="showTip">
请上传
<template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
<template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
的文件
</div> -->
<!-- 文件列表 -->
<transition-group
class="upload-file-list el-upload-list el-upload-list--text"
name="el-fade-in-linear"
tag="ul"
>
<li
:key="file.uid"
class="el-upload-list__item ele-upload-list__item-content"
v-for="(file, index) in fileList">
<el-link
:href="`${baseUrl}${file.url}`"
:underline="false"
target="_blank"
>
<span class="el-icon-document"> {{ getFileName(file.name) }} </span>
</el-link>
<div class="ele-upload-list__item-content-action">
<el-link :underline="false" #click="handleDelete(index)" type="danger"
>删除</el-link
>
</div>
</li>
</transition-group>
</div>
</template>
<script setup>
import { getToken } from "#/utils/auth";
const props = defineProps({
modelValue: [String, Object, Array],
// 数量限制
limit: {
type: Number,
default: 1,
},
// 大小限制(MB)
fileSize: {
type: Number,
default: 2,
},
// 文件类型, 例如['png', 'jpg', 'jpeg']
fileType: {
type: Array,
default: () => ["png", "jpg", "gif"],
},
// 是否显示提示
isShowTip: {
type: Boolean,
default: true,
},
});
const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const baseUrl = "URL HERE";
const uploadFileUrl = baseUrl + "Folder_URL"; //
const headers = ref({ Authorization: "Bearer " + getToken() });
const fileList = ref([]);
const showTip = computed(
() => props.isShowTip && (props.fileType || props.fileSize)
);
watch(
() => props.modelValue,
(val) => {
if (val) {
let temp = 1;
const list = Array.isArray(val) ? val : props.modelValue.split(",");
fileList.value = list.map((item) => {
if (typeof item === "string") {
item = { name: item, url: item };
}
item.uid = item.uid || new Date().getTime() + temp++;
return item;
});
} else {
fileList.value = [];
return [];
}
},
{ deep: true, immediate: true }
);
function handleBeforeUpload(file) {
if (props.fileType.length) {
let fileExtension = "";
if (file.name.lastIndexOf(".") > -1) {
fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
}
const isTypeOk = props.fileType.some((type) => {
if (file.type.indexOf(type) > -1) return true;
if (fileExtension && fileExtension.indexOf(type) > -1) return true;
return false;
});
if (!isTypeOk) {
proxy.$modal.msgError(
${props.fileType.join("/")}
);
return false;
}
}
if (props.fileSize) {
const isLt = file.size / 1024 / 1024 < props.fileSize;
if (!isLt) {
proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
return false;
}
}
proxy.$modal.loading("正在上传文件,请稍候...");
number.value++;
return true;
}
function handleExceed() {
proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}
function handleUploadError(err) {
proxy.$modal.msgError("上传文件失败");
}
// 上传成功回调
function handleUploadSuccess(res, file) {
uploadList.value.push({ name: res.fileName, url: res.fileName });
if (uploadList.value.length === number.value) {
fileList.value = fileList.value
.filter((f) => f.url !== undefined)
.concat(uploadList.value);
uploadList.value = [];
number.value = 0;
emit("update:modelValue", listToString(fileList.value));
proxy.$modal.closeLoading();
console.log("url", file);
}
}
// 删除文件
function handleDelete(index) {
fileList.value.splice(index, 1);
emit("update:modelValue", listToString(fileList.value));
}
// 获取文件名称
function getFileName(name) {
if (name.lastIndexOf("/") > -1) {
return name.slice(name.lastIndexOf("/") + 1);
} else {
return "";
}
}
// 对象转成指定字符串分隔
function listToString(list, separator) {
let strs = "";
separator = separator || ",";
for (let i in list) {
if (undefined !== list[i].url) {
strs += list[i].url + separator;
}
}
return strs != "" ? strs.substr(0, strs.length - 1) : "";
}
</script>
//tu
<style scoped lang="scss">
.upload-file-uploader {
margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
border: 1px solid #e4e7ed;
line-height: 2;
margin-bottom: 10px;
position: relative;
}
.upload-file-list .ele-upload-list__item-content {
display: flex;
justify-content: space-between;
align-items: center;
color: inherit;
}
.ele-upload-list__item-content-action .el-link {
margin-right: 10px;
}
</style>

Mute/UnMute Remote Attendee in Amazon Chime Sdk

How we can build Mute/UmMute Remote Attendee in Amazon Chime Sdk with the help of
(https://aws.github.io/amazon-chime-sdk-js/modules/apioverview.html#9-send-and-receive-data-messages-optional ) web sockets to broadcast a message in a meeting.
Currently, there is no option to mute/unmute Remote Attendee in Amazon Chime SDK
But yes we can use real-time messaging for that
Add `realtimeSubscribeToReceiveDataMessage` on attndeeId so when the user joins meeting then it will get the message on this channel.
like mentioned in the below code snip
import { Button } from 'react-bootstrap';
import React, { useContext, useEffect, useState } from 'react';
import getChimeContext from '../context/getChimeContext';
import useRoster from '../hooks/useRoster';
export default function RosterCompoment(props) {
const { realTimeRequestAttendees, leaveMeeting } = props;
const chime = useContext(getChimeContext());
const roster = useRoster();
const [videoAttendees, setVideoAttendees] = useState(new Set());
const [isVideo, setIsVideo] = useState(false);
const realtimeSubscribeToReceiveDataMessage = async () => {
chime.audioVideo &&
(await chime.audioVideo.realtimeSubscribeToReceiveDataMessage(chime.attendeeId, async (data) => {
const receivedData = (data && data.json()) || {};
const { type, name } = receivedData || {};
if ((type === 'UNMUTE' || type === 'VIDEO-ENABLE')) {
return;
}
if (type === 'UNMUTE') {
chime.audioVideo && (await chime.audioVideo.realtimeUnmuteLocalAudio());
} else if (type === 'MUTE') {
chime.audioVideo && (await chime.audioVideo.realtimeMuteLocalAudio());
} else if (type === 'KICK') {
await new Promise((resolve) => setTimeout(resolve, 200));
await chime.chooseVideoInputDevice(null);
chime.audioVideo && (await chime.audioVideo.stopContentShare());
chime.audioVideo && (await chime.audioVideo.stop());
if (leaveMeeting) leaveMeeting(); // You can call leave meeting function here to kick any user
} else if (type === 'VIDEO-DISABLE') {
chime.audioVideo && (await chime.audioVideo.stopLocalVideoTile());
} else if (type === 'VIDEO-ENABLE') {
await chime.chooseVideoInputDevice(chime.currentVideoInputDevice);
chime.audioVideo && (await chime.audioVideo.startLocalVideoTile());
}
}));
};
useEffect(() => {
realtimeSubscribeToReceiveDataMessage();
const tileIds = {};
const realTimeVideoAttendees = new Set();
const removeTileId = (tileId) => {
const removedAttendeeId = tileIds[tileId];
delete tileIds[tileId];
realTimeVideoAttendees.delete(removedAttendeeId);
setVideoAttendees(new Set(realTimeVideoAttendees));
};
chime.audioVideo &&
chime.audioVideo.addObserver({
videoTileDidUpdate: (tileState) => {
if (!tileState.boundAttendeeId || tileState.isContent || !tileState.tileId) {
return;
}
if (tileState.active) {
tileIds[tileState.tileId] = tileState.boundAttendeeId;
realTimeVideoAttendees.add(tileState.boundAttendeeId);
setVideoAttendees(new Set(realTimeVideoAttendees));
} else {
removeTileId(tileState.tileId);
}
},
videoTileWasRemoved: (tileId) => {
removeTileId(tileId);
},
});
}, []);
let attendeeIds;
if (chime.meetingSession && roster) {
attendeeIds = Object.keys(roster).filter((attendeeId) => !!roster[attendeeId].name);
}
return (
<div>
<div className="roster">
{attendeeIds &&
attendeeIds.map((attendeeId) => {
const rosterAttendee = roster[attendeeId];
return (
<div key={attendeeId} className="attendee">
<div className="name">{rosterAttendee.name}</div>
{ realTimeRequestAttendees && realTimeRequestAttendees.has(attendeeId) && (
<div className="">
<a
className="cursor"
onClick={() => {
realTimeRequestAttendees.delete(attendeeId);
chime.sendMessage(attendeeId, {
type: 'ADMIT',
});
}}
>
Answer
</a>
</div>
)}
<a
className="cursor"
onClick={() => {
chime.sendMessage(attendeeId, {
type: 'KICK',
});
}}
>
Remove
</a>
{videoAttendees && (
<div className="video">
<a
className="cursor"
onClick={() => {
chime.sendMessage(attendeeId, {
type: videoAttendees.has(attendeeId) ? 'VIDEO-DISABLE' : 'VIDEO-ENABLE',
});
}
}}
>
{videoAttendees.has(attendeeId) ? (
<i className="fa fa-video-camera" />
) : (
<i className="camera-icon-muted" />
)}
</a>
</div>
)}
{typeof rosterAttendee.muted === 'boolean' && (
<div className="muted">
<a
className="cursor"
onClick={() => {
chime.sendMessage(attendeeId, {
type: rosterAttendee.muted ? 'UNMUTE' : 'MUTE',
});
}}
>
{rosterAttendee.muted ? (
<i className="fa fa-microphone-slash" />
) : (
<i
className={cx(
'fa fa-microphone',
{ 'active-speaker': rosterAttendee.active },
{
'weak-signal': rosterAttendee.signalStrength && rosterAttendee.signalStrength < 50,
},
)}
/>
)}
</a>
</div>
)}
</div>
);
})}
</div>
</div>
);
}
Here is the method to send messages to remote attendees through his/her attndeeId.
sendMessage = (topic, data) => {
new AsyncScheduler().start(() => {
const payload = {
...data,
attendeeId: this.attendeeId || '',
name: this.rosterName || '',
};
this.audioVideo &&
this.audioVideo.realtimeSendDataMessage(topic, payload, ChimeSdkWrapper.DATA_MESSAGE_LIFETIME_MS);
this.publishMessageUpdate(
new DataMessage(
Date.now(),
topic,
new TextEncoder().encode(payload),
this.meetingSession.configuration.credentials.attendeeId || '',
this.meetingSession.configuration.credentials.externalUserId || '',
),
);
});
};```

Not closing camera in zxing

In the Zxing library, I want to close the camera when the user clicks cancel. So I used a button and add onclick event to it. it is calling resetReader method. I called this method after gets a barcode value or in the cancel button onclick event.If it is getting barcode values, this resetReader method works perfectly. if we cancel, the camera doesn't stop. Am I missing something?
const codeReader = new BrowserMultiFormatReader(hints);
const resetReader = () => {
codeReader.reset();
codeReader.stopContinuousDecode();
};
for those who haven't figured it out yet? I have found a solution to this problem. Harendrra's solution didn't work for me, but this one did in combination with usestate. For my project the code uses Bootstrap. So when I click on a button the Modal appears. The camera loads. When I click on the Close button the camera disappears. Hope this is a solutions for everyone, enjoy ;-)
export default function Example(props) {
// codeReader
const [codeReader, setReader] = useState(new BrowserMultiFormatReader());
const [videoInputDevices, setVideoInputDevices] = useState([]);
const [selectedVideoDevice, selectVideoDevice] = useState('');
useEffect(() => {
(async () => {
const videoInputDeviceList = await codeReader.listVideoInputDevices();
setVideoInputDevices(videoInputDeviceList);
if (videoInputDeviceList.length > 0 && selectedVideoDevice == null) {
selectVideoDevice(videoInputDeviceList[0].deviceId);
}
})();
}, [codeReader, selectedVideoDevice]);
const handleShow = () => {
setBrand('');
// Open modal.
setShow(true);
codeReader.decodeFromVideoDevice(selectedVideoDevice, 'videoElement', (res) => {
setCanClose(true);
if (res) {
const rawText = res.getText();
axios
.get(`https://world.openfoodfacts.org/api/v0/product/${rawText}.json`)
.then((result) => {
// set data
setBrand(result.data.product.brands);
// close modal
setShow(false);
// codeReader reset
codeReader.reset();
})
.catch((err) => console.log('error', err));
}
});
};
const handleClose = () => {
// codeReader reset.
setReader(codeReader.reset());
// Close modal
setShow(false);
// Set new codeReader.
// The solution for the error messages after the codeReader reset.
// This will build the codeReader for the next time.
setReader(new BrowserMultiFormatReader(hints));
};
return (
<Fragment>
<div className='py-2'>
<div>Brand: {brand}</div>
<Button variant='primary' onClick={handleShow}>
Launch static backdrop modal
</Button>
<Modal show={show} onHide={handleClose} backdrop='static' keyboard={false} centered id='scanProductModal'>
<Modal.Body>
<div
onChange={(event) => {
const deviceId = event.target.value;
selectVideoDevice(deviceId);
}}
>
<div className='button-group-top'>
<select className='form-select form-select-sm' aria-label='Default select example'>
{videoInputDevices &&
videoInputDevices.map((inputDevice, index) => {
return (
<option value={inputDevice.deviceId} key={index}>
{inputDevice.label || inputDevice.deviceId}
</option>
);
})}
</select>
</div>
<video id='videoElement' width='600' height='400' />
<Button className='btn btn-danger' onClick={handleClose}>
Close
</Button>
</div>
</Modal.Body>
</Modal>
</Fragment>
);
}
Yes, I resolved. You have to create codeReader object at the top of the Class. Try this code.
import "../App.css";
import { BrowserBarcodeReader } from "#zxing/library";
class Barcode extends React.Component {
codeReader = new BrowserBarcodeReader();
constructor(props) {
super(props);
this.state = { reader: {}, selectedDevice: "" };
this.startButton = this.startButton.bind(this);
this.resetButton = this.resetButton.bind(this);
this.getBarcode = this.getBarcode.bind(this);
}
componentDidMount() {
this.getBarcode();
}
startButton() {
console.log("start", this.codeReader);
this.codeReader
.decodeOnceFromVideoDevice(this.state.selectedDevice, "video")
.then(result => {
document.getElementById("result").textContent = result.text;
})
.catch(err => {
console.error(err.toString());
document.getElementById("result").textContent = err;
});
console.log(
`Started continous decode from camera with id ${this.state.selectedDevice}`
);
}
resetButton() {
this.codeReader && this.codeReader.reset();
document.getElementById("result").textContent = "";
}
getBarcode() {
let selectedDeviceId;
return this.codeReader.getVideoInputDevices().then(videoInputDevices => {
const sourceSelect = document.getElementById("sourceSelect");
selectedDeviceId = videoInputDevices[0].deviceId;
if (videoInputDevices.length > 1) {
videoInputDevices.forEach(element => {
const sourceOption = document.createElement("option");
sourceOption.text = element.label;
sourceOption.value = element.deviceId;
sourceSelect.appendChild(sourceOption);
});
sourceSelect.onchange = () => {
selectedDeviceId = sourceSelect.value;
};
const sourceSelectPanel = document.getElementById(
"sourceSelectPanel"
);
sourceSelectPanel.style.display = "block";
}
this.setState({
selectedDevice: selectedDeviceId
});
})
.catch(err => {
alert(err);
});
}
render() {
return (
<div>
<h2>Barcode</h2>
{Object.keys(this.codeReader).length > 0 && (
<div>
<div>
<button
className="button"
id="startButton"
onClick={this.startButton}
>
Start
</button>
<button
className="button"
id="resetButton"
onClick={this.resetButton}
>
Reset
</button>
</div>
<div>
<video
id="video"
width="600"
height="400"
style={{ border: "1px solid gray" }}
></video>
</div>
<label>Result:</label>
<pre>
<code id="result"></code>
</pre>
</div>
)}
</div>
);
}
}
export default Barcode; ```

How to use setFieldValue and pass the value as props between components

I'm trying to use ant design forms in my sample registration form, when i'm trying to use setFieldsValue it throws error as "Cannot use setFieldsValue unless getFieldDecorator is used". But I had already used getFieldDecorator in my code.Here is a sample of my code.
handleChange = (e) => {
const fname = e.target.name;
const fvalue = e.target.value;
this.props.setFieldsValue({
fname: fvalue
});
}
render(){
const { getFieldDecorator } = this.props.form
return (
<Row gutter={4}>
<Col className="reg-personal-details-grid-column" span={24}>
<FormItem {...formItemLayout} label="First Name">
{getFieldDecorator("firstName", {
rules: [
{
required: true
}
]
})(
<Input
placeholder="First Name"
required
name="firstName"
onChange={this.handleChange}
/>
)}
</FormItem>
</Col>
</Row>
)
}
fname is not defined in getFieldDecorator.
You should do this:
handleChange = (e) => {
const fname = e.target.name;
const fvalue = e.target.value;
this.props.form.setFieldsValue({
[fname]: fvalue
});
}
You can create your own function to do this:
export const setFieldValue = (
form: FormInstance,
name: NamePath,
value: string
): void => {
if (form && form.getFieldValue(name)) {
const fixname: string[] = [];
if (typeof name == 'object') {
name.forEach((node: string) => {
fixname.push(node);
});
} else {
fixname.push(String(name));
}
let fieldsValue: unknown;
fixname.reverse().forEach((node: string) => {
fieldsValue = {
[String(node)]: fieldsValue != undefined ? fieldsValue : value,
};
});
form.setFieldsValue(fieldsValue);
}
};
and you can use like that
setFieldValue(form, 'phone', '1111111111');
or
setFieldValue(form, ['phones', 'mobile'], '2222222222');
In Antd v4, you only required to call the setFieldsValue in useEffect function.
const [form] = Form.useForm()
useEffect(() => {
//companyInfo -> dynamic obj fetched from API
form.setFieldsValue(companyInfo);
}, [companyInfo, form]);
Then in Form use the form prop as follow:
<Form
//passing form prop
form={form}
labelCol={{ span: 8 }}
wrapperCol={{ span: 14 }}
onFinish={onFinish}
labelAlign="left"
colon={false}
>
you can use it like this
const formRef = useRef(null);
useEffect(() => {
formRef.current?.setFieldsValue({
name: data?.firstName,
});
}, [data]);
return (
<Form ref={formRef}>
<Form.Item name="name">
<Input/>
</Form.Item>

converting from blob to binary to save it to mongodb

I get the object like that from the front end to my node express server.
{ picture: [ { preview: 'blob:http://localhost:3000/1f413443-83d8-499e-a432-9ac51a2592b7' } ],
name: 'fsdfs',
description: 'fdfd',
url: 'fdfd',
about: 'dfdf' }
i get this error :
TypeError: path must be a string or Buffer
at TypeError (native)
this is my function where i save to the mongodb
exports.create_a_project = function(req, res) {
console.log(req.body);
var new_project = new Project(req.body);
new_project.picture.data = fs.readFileSync(req.body.picture[0]);
new_project.picture.contentType = 'image/png';
new_project.save(function(err, project) {
if (err)
res.send(err);
res.json(project);
});
};
some how i need to convert the image i am receiving to be binary in order to save.
or i need to send it as a binary base64 from the client side it self.
my client side i use react redux Dropzone for sending my data.
here is my form and how it look like.
import React from 'react';
import {Field, reduxForm} from 'redux-form';
import Dropzone from 'react-dropzone';
const FILE_FIELD_NAME = 'picture';
const renderDropzoneInput = (field) => {
const files = field.input.value;
return (
<div>
<Dropzone
name={field.name}
onDrop={(filesToUpload, e) => field.input.onChange(filesToUpload)}
>
<div>Try dropping some files here, or click to select files to
upload.
</div>
</Dropzone>
{field.meta.touched &&
field.meta.error &&
<span className="error">{field.meta.error}</span>}
{files && Array.isArray(files) && (
<ul>
{files.map((file, i) => <li key={i}>{file.name}</li>)}
</ul>
)}
</div>
);
};
const validate = values => {
const errors = {};
if (!values.name) {
errors.name = 'Required';
} else if (values.name.length > 15) {
errors.name = 'Must be 15 characters or less';
}
if (!values.description) {
errors.description = 'Required';
} else if (values.description.length > 15) {
errors.description = 'Must be 75 characters or less';
}
if (!values.url) {
errors.url = 'Required';
} else if (values.url.length > 15) {
errors.url = 'Must be 15 characters or less';
}
if (!values.about) {
errors.about = 'Required';
} else if (values.about.length > 15) {
errors.about = 'Must be 15 characters or less';
}
if (!values.picture) {
errors.picture = 'Required';
} else if (values.picture.length > 15) {
errors.picture = 'Must be 15 characters or less';
}
// if (!values.email) {
// errors.email = 'Required';
// } else if (!/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
// errors.email = 'Invalid email address';
// }
// if (!values.age) {
// errors.age = 'Required';
// } else if (isNaN(Number(values.age))) {
// errors.age = 'Must be a number';
// } else if (Number(values.age) < 18) {
// errors.age = 'Sorry, you must be at least 18 years old';
// }
return errors;
};
const warn = values => {
const warnings = {};
// if (values.age < 19) {
// warnings.age = 'Hmm, you seem a bit young...';
// }
return warnings;
};
const renderField = ({input, label, type, meta: {touched, error, warning}}) => (
<div>
<label>{label}</label>
<div>
<input {...input} placeholder={label} type={type}/>
{touched && ((error && <span>{error}</span>) ||
(warning && <span>{warning}</span>))}
</div>
</div>
);
const SyncValidationForm = (props) => {
const {handleSubmit, pristine, reset, submitting} = props;
return (
<form onSubmit={handleSubmit}>
<Field name="name" type="text" component={renderField}
label="Name"/>
<Field name="description" type="text" component={renderField}
label="Description"/>
<Field name="url" type="text" component={renderField}
label="Url"/>
<Field name="about" type="text" component={renderField}
label="About"/>
{/*<Field name="picture" type="text" component={renderField}*/}
{/*label="Picture"/>*/}
<Field
name={FILE_FIELD_NAME}
component={renderDropzoneInput}
/>
{/*<Field name="email" type="email" component={renderField} label="Email"/>*/}
{/*<Field name="age" type="number" component={renderField} label="Age"/>*/}
<div>
<button type="submit" disabled={submitting}>Submit</button>
<button type="button" disabled={pristine || submitting}
onClick={reset}>Clear Values
</button>
</div>
</form>
);
};
export default reduxForm({
form: 'syncValidation', // a unique identifier for this form
validate, // <--- validation function given to redux-form
warn // <--- warning function given to redux-form
})(SyncValidationForm);
this is my service function which deals with the rest api.
const addProject = (newProject) => {
let data = JSON.stringify(newProject);
return axios.post('http://localhost:3008/projects', data, {
headers: {
'Content-Type': 'application/json',
}
}
).then(response => {
// console.log(response)
}).catch(error => {
console.log(error)
});
};
So I think your problem is in this line:
new_project.picture.data = fs.readFileSync(req.body.picture[0]);
And it's the mongoDB table column that you are inserting data into that is giving you that error. It's expecting a string or Buffer and you gave it a File object.
You can get a base64 byte string using what I posted here, which I'll try and integrate with your code, below:
You'd need to ensure you have a variable to collect your file(s). This is how I have the top of my page set up:
import React from 'react'
import Reflux from 'reflux'
import {Form, Card, CardBlock, CardHeader, CardText, Col, Row, Button } from 'reactstrap'
import actions from '~/actions/actions'
import DropZone from 'react-dropzone'
// stores
import SomeStore from '~/stores/someStore.jsx'
Reflux.defineReact(React)
export default class myUploaderClass extends Reflux.Component {
constructor(props) {
super(props);
this.state = {
attachments: [],
};
this.stores = [
SomeStore,
]
....
Then bind new functions:
....
this.getData = this.getData.bind(this);
this.processFile = this.processFile.bind(this);
this.errorHandler = this.errorHandler.bind(this);
this.progressHandler = this.progressHandler.bind(this);
} // close constructor
Then we work on supplying the bytes to attachments and sending it to new_project.picture.data. For me, I use a function that runs onDrop of the DropZone using onDrop={this.uploadFile}. I can't really tell what you're doing because I have no clue what filesToUpload refers to. My uploadFile looks like this:
uploadFile(event){
this.setState({
files: event,
});
document.getElementById('docDZ').classList.remove('dragover');
document.getElementById('progress').textContent = '000';
document.getElementById('progressBar').style.width = '0%';
this.state.files = event; // just for good measure
for (let i = 0; i < this.state.files.length; i++) {
const a = i + 1;
console.log('in loop, pass: ' + a);
const f = this.state.files[i];
this.getData(f); // this will load the file to SomeStore.state.attachments
}
}
and this would be the getData function ran for each file dropped/added to the DropZone:
getData(f) {
const reader = new FileReader();
reader.onerror = this.errorHandler;
reader.onprogress = this.progressHandler;
reader.onload = this.processFile(f);
reader.readAsDataURL(f);
}
Then processFile() from the onload runs:
processFile(theFile) {
return function(e) {
const bytes = e.target.result.split('base64,')[1];
const fileArray = [];
// *** Collect any existing attachments ***
// I found I could not get it from this.state, but had to use
// my store, instead
if (SomeStore.state.attachments.length > 0) {
for (let i=0; i < SomeStore.state.attachments.length; i++) {
fileArray.push(SomeStore.state.attachments[i]);
}
}
// Add the new one to this.state
fileArray.push(bytes);
// Update the state
SomeStore.setState({
attachments: fileArray,
});
// This seemed to automatically add it to this.state, for me.
}
}
Once you have that, you should be able to do:
new_project.picture.data = this.state.attachments[0];
If not, for some reason, you might try to call this inside exports.create_a_project(), as the first thing you do:
getData(req.body.picture[0]);
This might even work without having to modify your onDrop routine from what you have. And if this.state.attachments doesn't have anything, your SomeStore.state.attachments definitely should, assuming you have this saved to a folder called stores as someStore.jsx.
import Reflux from 'reflux'
import Actions from '~/actions/actions`
class SomeStore extends Reflux.Store
{
constructor()
{
super();
this.state = {
attachments: [],
};
this.listenables = Actions;
this.baseState = {
attachments: [],
};
}
onUpdateFields(name, value) {
this.setState({
[name]: value,
});
}
onResetFields() {
this.setState({
attachments: [],
});
}
}
const reqformdata = new SomeStore
export default reqformdata
Additional functions
errorHandler(e){
switch (e.target.error.code) {
case e.target.error.NOT_FOUND_ERR:
alert('File not found.');
break;
case e.target.error.NOT_READABLE_ERR:
alert('File is not readable.');
break;
case e.target.error.ABORT_ERR:
break; // no operation
default:
alert('An error occurred reading this file.');
break;
}
}
progressHandler(e) {
if (e.lengthComputable){
const loaded = Math.round((e.loaded / e.total) * 100);
let zeros = '';
// Percent loaded in string
if (loaded >= 0 && loaded < 10) {
zeros = '00';
}
else if (loaded < 100) {
zeros = '0';
}
// Display progress in 3-digits and increase bar length
document.getElementById("progress").textContent = zeros + loaded.toString();
document.getElementById("progressBar").style.width = loaded + '%';
}
}
And my DropZone & applicable progress indicator markup:
render(){
const dropZoneStyle = {
height: "34px",
width: "300px",
border: "1px solid #ccc",
borderRadius: "4px",
};
return (
<Form>
<Col xs={5}>
<DropZone type="file" id="docDZ"
onDrop={this.uploadFile}
onDropRejected={this.onDropRejected}
onClick={this.handleUploadClick}
onChange={this.handleChange}
onDragEnter={this.handleDragEnter}
onDragLeave={this.handleDragLeave}
accept=".doc, .docx, .gif, .png, .jpg, .jpeg, .pdf"
multiple="true"
maxSize={999000}
style={dropZoneStyle}>
{'Click HERE to upload or drop files here...'}
</DropZone>
<table id="tblProgress">
<tbody>
<tr>
<td><b><span id="progress">000</span>%</b> <span className="progressBar"><span id="progressBar" /></span></td>
</tr>
</tbody>
</table>
</Col>
</Row>
</Form>
)
} // close render
} // close class
And CSS:
.progressBar {
background-color: rgba(255, 255, 255, .1);
width: 100%;
height: 26px;
}
#progressBar {
background-color: rgba(87, 184, 208, .5);
content: '';
width: 0;
height: 26px;
}
Other functions you're missing:
handleUploadClick(){
return this.state;
}
handleChange(){
this.state.errors.fileError = "";
}
handleDragEnter(event){
event.preventDefault();
document.getElementById("docDZ").classList.add("dragover");
}
handleDragLeave(event){
event.preventDefault();
document.getElementById("docDZ").classList.remove("dragover");
}
onDropRejected(files){
const errors ={}
let isAlertVisible = false;
for(let i=0, j = files.length; i < j; i++){
const file = files[i];
const ext = file.name.split('.').pop().toLowerCase();
//console.log(ext)
if(this.isFileTypeValid(ext)===false){
errors.fileError = "Only image files (JPG, GIF, PNG), Word files (DOC, DOCX), and PDF files are allowed.";
isAlertVisible = true;
}
if(ext === "docx" || ext ==="gif" || ext ==="png" || ext ==="jpg" || ext ==="jpeg" || ext ==="pdf" || ext ==="doc" && file.size > 999000){
errors.fileError = "Exceeded File Size limit! The maximum file size for uploads is 999 KB.";
isAlertVisible = true;
}
this.setState({
"errors": errors,
"isAlertVisible": isAlertVisible,
})
}
}