`templates/index.html`

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Index</title>
</head>

<body>
    <input type="file" name="file" id="myfile">
    <script type="text/javascript">
	    const input = document.getElementById('myfile');
	    const upload = (file) => {
	        fetch('/v1/upload', {
	            method: 'POST',
	            headers: {
	                "Content-Type": "multipart/form-data"
	            },
	            body: file
	        }).then(
	            response => response.text()
	        ).then(
	            success => console.log(success)
	        ).catch(
	            error => console.log(error)
	        );
	    };
	    const onSelectFile = () => upload(input.files[0]);
	    input.addEventListener('change', onSelectFile, false);
    </script>


<!-- source: https://stackoverflow.com/questions/36067767/how-do-i-upload-a-file-with-the-js-fetch-api -->
</body>

</html>

2021-11-16  ·  5 次查看  ·  V2EX