过去几个小时我一直在尝试模块和库。从socketio-fileupload 到其他类似的。没有一个对我有用。如果可能的话,我只想要一些基本且简单的东西。我无法将文件传输到服务器。我怎样才能以最少的麻烦做到这一点?
html
<input required type='file' id="imageUpload" accept=".png, .jpg, .jpeg" />
<button class="saveImage">Upload Image</button>
客户
function updateAvatar(){
$('.saveImage').on('click',function(){
var file = $('#imageUpload').val();
var filename = file.name;
var filesize = file.size;
var enc = file.encoding;
console.log(file);
socket.emit('update-avatar', {
data : file,
size : filesize,
name : filename,
enc : enc
}
);
});
}
服务器
socket.on('update-avatar',function(data){
console.log(data);
var filename = path.basename(data.name);
var filepath = path.join('./uploads', filename);
});
这里是使用 socketio 将图像上传到 Nodejs 的简单方法。使用 FileReader() 为我工作。不需要库,只需通过 Base64 发送所有内容即可。您确实需要
fs
模块(npm install fs
)。我把全部内容都贴在这里了。
通过此代码片段,您将能够
//load fs module
const fs = require('fs');
/*
Upload file to folder
Send image back to client to display in real time
*/
socket.on('update-avatar',function(json){
//variables
var image = json.data.file;
var data = image.replace(/^data:image\/\w+;base64,/, '');
var fileName = 'user'+userid+Date.now() + "image.png";
//upload to folder
fs.writeFile("../user/upload/" + fileName, data, {encoding: 'base64'}, function(err){
if(err){
console.log(err);
}else{
//success
//return image back to js-client
io.to(socketid).emit('avatar-updated',{valid:'true',message:'success',buffer: data.toString('base64')
});
}
});
});
/*
DISPLAY AVATAR
*/
document.getElementById("imageUpload").onchange = function () { displayAvatar() };
function displayAvatar() {
const file = document.getElementById("imageUpload").files[0];
const reader = new FileReader();
reader.onloadend = function () {
document.getElementById('clock').style.backgroundImage = "url(" + reader.result + ")";
$('.saveImage').show('slow');
$('.cancelImage').show('slow');
}
if (file) {
reader.readAsDataURL(file);
} else {
}
}
/*
UPLOAD AVATAR
*/
function updateAvatar(){
$(".saveImage").on('click', function() {
// validate type of file
if(['image/jpeg', 'image/jpg', 'image/png', 'image/gif'].indexOf($("#imageUpload").get(0).files[0].type) == -1) {
alert('Error : Only JPEG, PNG & GIF allowed');
return;
}
var reader = new FileReader();
reader.onload = function(){
var $data = {'file': reader.result };
//send
socket.emit('update-avatar',{data:$data});
};
reader.readAsDataURL($("#imageUpload").get(0).files[0]);
});
}
/*FILE UPLOAD AVATAR.HTML*/
.avatar-upload {
position: relative;
max-width: 205px;
margin: 50px auto;
}
.avatar-upload .avatar-edit {
position: absolute;
right: 12px;
z-index: 1;
top: 10px;
}
.avatar-upload .avatar-edit input {
display: none;
}
.avatar-upload .avatar-edit input + label {
display: inline-block;
width: 34px;
height: 34px;
margin-bottom: 0;
border-radius: 100%;
background: #FFFFFF;
border: 1px solid transparent;
box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.12);
cursor: pointer;
font-weight: normal;
transition: all 0.2s ease-in-out;
}
.avatar-upload .avatar-edit input + label:hover {
background: #f1f1f1;
border-color: #d6d6d6;
}
.avatar-upload .avatar-edit input + label:after {
font-family: 'FontAwesome';
color: #757575;
position: absolute;
top: 10px;
left: 0;
right: 0;
text-align: center;
margin: auto;
}
.avatar-upload .avatar-preview {
width: 192px;
height: 192px;
position: relative;
border-radius: 100%;
text-align: center !important;
border: 6px solid grey;
box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
}
.avatar-upload .avatar-preview > div {
background-image: url('');
width: 100%;
height: 100%;
border-radius: 100%;
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
.saveImage{
display:none;
}
.cancelImage{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list no-border">
<div class="item">
<div class="avatarContainer">
<div class="avatar-upload">
<div class="avatar-edit">
<input required type='file' id="imageUpload" accept=".png, .jpg, .jpeg" />
<label class="ion icon ion-camera text-grey" for="imageUpload"><img style="width:35px;" src="https://www.islesburghdramagroup.com/wp-content/uploads/2015/07/Image-Edition-Tools-Screenshot-icon.png" /></label>
</div>
<div class="avatar-preview">
<div id="clock" style="background-image: url(img/icon.png);">
</div>
</div>
</div>
</div>
</div>
<div style="text-align:center;" class="item align-center">
<button class="icon ion ion-checkmark-round saveImage green button">Save</button>
<button id="cancelImage" class="icon ion ion-close-round cancelImage red button">Cancel</button>
</div>
</div>
客户
socket.emit('upload', input.files[0], (obj) => {
output.innerHTML = obj.message;
});
服务器
let express = require('express');
let app = express();
let server = require('http').Server(app);
let io = require('socket.io')(server, {
cors: {
origin: 'http://localhost:3000',
},
maxHttpBufferSize: 1e8
});
let { writeFile } = require('fs');
io.on('connection', async (socket) => {
socket.on('upload', async (buffer, cb) => {
let dir = './static/images/';
let filename = Date.now().toString(16) + '.png';
let url = dir + filename;
writeFile(url, buffer, (err) => {
cb({ message: err ? 'Error! Failed to add file!' : 'File ' + filename + ' added to the server. });
});
});
});