Skip to content

Commit

Permalink
form to edit the name
Browse files Browse the repository at this point in the history
  • Loading branch information
aloxe committed Jul 23, 2024
1 parent 008a6a0 commit 2a8b14b
Show file tree
Hide file tree
Showing 4 changed files with 163 additions and 93 deletions.
19 changes: 14 additions & 5 deletions public/datavelo/api/uploadfile.php
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
<?php

$name = $_FILES['file']['name'];

if (substr($name, -4, 4) == ".gpx") {
$newname = '../gpx/'.$name;
// temporarly follow naming scheme on gpx
if (substr($name, -7, 1) == ".") {
$cc = substr($name, -7, 3);
$root = substr($name, 0, -7);
} else {
$cc = ".xx";
$root = substr($name, 0, -4);
}
$newname = $root.'-php'.$cc.'.gpx';
$newpath = '../gpx/'.$newname;

if (move_uploaded_file( $_FILES['file']['tmp_name'], $newname)) {
// send_OK();
$data = array('status' => 201, 'message' => '🐝 File written \o/ ('.$name.')', 'name' => $name);
if (move_uploaded_file( $_FILES['file']['tmp_name'], $newpath)) {
$data = array('status' => 201, 'message' => '🐝 File written \o/ ('.$name.')', 'name' => $newname);
} else {
$data = array("status"=> '0', "message"=> '☹ File NOT saved :o( ');
}
} else {
$data = array("status"=> '0', "message"=> '☹ File NOT saved (not a gpx)');
$data = array("status"=> '0', "message"=> '☹ File NOT saved (not a gpx)');
}

echo json_encode($data);
Expand Down
42 changes: 36 additions & 6 deletions src/components/FileUpload.css
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,46 @@
}

.progress-value {
animation: load 3s normal forwards;
animation: load 1s normal forwards;
background: teal;
height: 10px;
/* width: 0; */
font-size: smaller;
font-size: x-small;
color: white;
}

/* @keyframes load {
@keyframes load {
0% { width: 0; }
100% { width: 100%; }
} */

}

form {
/* max-width: 400px; */
width: 80%;
margin: 0 auto;
display: flex;
flex-direction: row;
}

form label{
text-align: left;
display: flex;
flex-direction: column;
font-size: smaller;
padding-right: 20px;
}
form input.date {
width: 100px;
}
form input.title {
width: 300px;
}
form input.countries {
width: 80px;
}

form + div {
padding: 10px 0;
text-align: left;
width: 80%;
margin: 0 auto;
}
156 changes: 100 additions & 56 deletions src/components/FileUpload.jsx
Original file line number Diff line number Diff line change
@@ -1,65 +1,84 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import Dropzone from "react-dropzone";
import { uploadFile } from "../helpers/gpxUtil";
import { loadGeoJson, uploadFile } from "../helpers/gpxUtil";
import './FileUpload.css'
import { toSlug } from "../helpers/strings";

// https://www.bezkoder.com/react-hooks-file-upload/

const FileUpload = () => {
const [selectedFiles, setSelectedFiles] = useState(undefined);
const [currentFile, setCurrentFile] = useState(undefined);
const [currentGpx, setcurrentGpx] = useState(undefined);
const [currentName, setcurrentName] = useState(undefined);
const [currentGeoJson, setCurrentGeoJson] = useState(undefined);
const [progress, setProgress] = useState(0);
const [message, setMessage] = useState("");
const [fileInfos, setFileInfos] = useState([]);

const [form, setForm] = useState({
date: '',
title: '',
countries: [],
});

useEffect(() => {
const getGeoJsonAwaited = async (name) => {
const geojson = await loadGeoJson(name);
setCurrentGeoJson(geojson);
}
if (currentName) {
getGeoJsonAwaited(currentName)
}
}, [currentName]);

useEffect(() => {
console.log("useEffect", currentGeoJson);
if (currentGeoJson) {
setForm({
date: currentGeoJson.date,
title: currentGeoJson.title,
countries: currentGeoJson.countries
})
}
}, [currentGeoJson]);

const onDrop = (files) => {
if (files.length > 0) {
setSelectedFiles(files);
}
};

const upload = () => {
let currentFile = selectedFiles[0];
const uploadgpx = async () => {
let currentGpx = selectedFiles[0];

setProgress(0);
setCurrentFile(currentFile);
setcurrentGpx(currentGpx);

uploadFile(currentFile, (event) => {
const fileName = await uploadFile(currentGpx, (event) => {
setProgress(Math.round((100 * event.loaded) / event.total));
})
.then((response) => {
setMessage(response.data.message);
// return getFiles();
})
.then((files) => {
setFileInfos(files.data);
})
.catch(() => {
setProgress(0);
setMessage("Could not upload the file!");
setCurrentFile(undefined);
});

setSelectedFiles(undefined);
setcurrentName(fileName)
};

const mystyle = {
width: {progress}+'%'
const uploadjson = async () => {
console.log("CLICK!");
console.log("form", form);
console.log("geojson", currentGeoJson);
// geojson.date = getDate(url)
// geojson.title = getTitle(url)
// geojson.countries = getCountries(url)
// geojson.distance = getDistance(geojson)
// geojson.slug = geojson.date + toSlug(geojson.title)
};

// const mystyle(progress) = {
// width: {progress}+'%',
// background: "red",
// };

return (
<div>
<div className="progress">
<div className="progress-value" style={mystyle} >{progress}%</div>
</div>



{currentFile && (
<div className="progress mb-3">
<ol style="--length: 5" role="list">
<li style="--i: 1">{progress}%</li>
</ol>
</div>
)}
{currentGpx && (<div className="progress">
<div className="progress-value" style={{width: `${progress}%`}} >{progress}%</div>
</div>)}


<Dropzone onDrop={onDrop} multiple={false}>
Expand All @@ -81,31 +100,56 @@ const FileUpload = () => {
<button
className="btn btn-success"
disabled={!selectedFiles}
onClick={upload}
onClick={uploadgpx}
>
Upload
Upload GPX
</button>
</aside>
</section>
)}
</Dropzone>

<div className="alert alert-light" role="alert">
{message}
</div>

{fileInfos.length > 0 && (
<div className="card">
<div className="card-header">List of Files</div>
<ul className="list-group list-group-flush">
{fileInfos.map((file, index) => (
<li className="list-group-item" key={index}>
<a href={file.url}>{file.name}</a>
</li>
))}
</ul>
</div>
)}
{currentGeoJson && <div className="card">
<form>
<label>Date:
<input type="text" className="date" name="date" value={form.date} onChange={e => {
setForm({
...form,
date: e.target.value
});
}}/>
</label>
<label>Title:
<input type="text" className="title" name="title" value={form.title} onChange={e => {
setForm({
...form,
title: e.target.value
});
}}/>
</label>
<label>
Countries:
<input type="text" className="countries" name="countries" value={form.countries.toString()} onChange={e => {
setForm({
...form,
countries: e.target.value.split(',')
});
}}/>
</label>
<div></div>
</form>
<div><b>Filename:</b> {`${form.date}-${form.title && toSlug(form.title.trim())}${form.countries.map(cc=>`.${cc}`).join('')}.json`}
</div>
<aside className="selected-file-wrapper">
<button
className="btn btn-success"
disabled={!selectedFiles}
onClick={uploadjson}
>
Upload GeoJson
</button>
</aside>
</div>}
</div>
);
};
Expand Down
39 changes: 13 additions & 26 deletions src/helpers/gpxUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export const filterGpxList = (currentYear, currentCountry, allGpxList) => {
}

export const loadGeoJson = async (url) => {
console.log("loadGeoJson");
try {
const response = await axios.get('https://alix.guillard.fr/data/velo/gpx/'+url);
const xmlDom = new DOMParser().parseFromString(response.data, 'application/xml');
Expand All @@ -39,14 +40,15 @@ export const loadGeoJson = async (url) => {
const featuresFiltered = geojson && geojson.features.filter(feature => feature.geometry.type !== "Point");
geojson.features = featuresFiltered
}
console.log("cleaned " + url);
// adding metadata
geojson.date = getDate(url)
geojson.title = getTitle(url)
geojson.countries = getCountries(url)
geojson.distance = getDistance(geojson)
geojson.slug = geojson.date + toSlug(geojson.title)
// save geojson so we don't need gpx after that
uploadJson(geojson) // already done
// uploadJson(geojson) // already done
return geojson;
} catch (error) {
console.error('Error fetching gpx data:', error.message);
Expand All @@ -68,40 +70,25 @@ export const uploadJson = async (geodata) => {
}
}

export const uploadFile = (file, onUploadProgress) => {
// const uploadForm = document.getElementById('uploadForm');
export const uploadFile = async (file, onUploadProgress) => {
let formData = new FormData();

formData.append("file", file);
return axios.post('https://alix.guillard.fr/data/velo/api/uploadfile.php', formData, {
const response = await axios.post('https://alix.guillard.fr/data/velo/api/uploadfile.php', formData, {
headers: {
"Content-Type": "multipart/form-data",
},
onUploadProgress,
});
const { data } = response;
if (data.status === 201) {
console.log("💾 " + data.message)
return data.name;
} else {
console.error("💢💢💢 " + data.message + " PAS SAUVÉ")
return null;
}
};

// const options = {
// method: 'POST',
// body: JSON.stringify(data),
// headers: { 'Content-Type': 'application/json' }
// }

// fetch("/api/upload.php", options)
// .then(response => response.json())
// .then(data => {
// if (data.status === 201)
// console.log("message", "💾 Données " + data.type + " sauvegardées")
// else
// console.error("message", "💢💢 Données " + data.type + " PAS SAUVÉES")
// })
// .catch(error => {
// console.error(error)
// console.error("message", "💢💢 visites " + data.type + " Pas sauvegardées : " + error)
// });
// }


function getBoundingBox(data) {
var bounds = {}, coords, latitude, longitude;
if (!data) return;
Expand Down

0 comments on commit 2a8b14b

Please sign in to comment.