Javascript 如何使用Socket IO上传图像文件?
我正在学校制作一个聊天应用程序作为一个项目,我正在尝试添加一个onClick来运行一个函数,它使用socket io文件上传来运行一个提示函数。 从套接字io文件上载文档。 调用此方法时,将提示用户选择要上载的文件Javascript 如何使用Socket IO上传图像文件?,javascript,node.js,reactjs,express,socket.io,Javascript,Node.js,Reactjs,Express,Socket.io,我正在学校制作一个聊天应用程序作为一个项目,我正在尝试添加一个onClick来运行一个函数,它使用socket io文件上传来运行一个提示函数。 从套接字io文件上载文档。 调用此方法时,将提示用户选择要上载的文件 JavaScript: document.getElementById("file_button").addEventListener("click", instance.prompt, false); HTML: <button id="file_button">U
JavaScript:
document.getElementById("file_button").addEventListener("click", instance.prompt, false);
HTML:
<button id="file_button">Upload File</button>
后端-
www.js-
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('cryptidbackend:server');
var http = require('http').createServer(app);
const io = require('socket.io')(http);
const siofu = require('socketio-file-upload')
const cors = require('cors');
app.use(cors());
// Socket.io
io.on('connection', function (socket) {
const uploader = new siofu(socket);
uploader.prompt(document.getElementById("InputAddon"))
uploader.listen(socket)
socket.on('sent message', function (msg) {
console.log('message' + ' : ' + JSON.stringify(msg))
socket.broadcast.emit('message', msg);
})
})
/**
* Get port from environment and store in Express.
*/
http.listen(3001, function () {
console.log('listening on 3001')
})
app.js-
const siofu = require('socketio-file-upload')
const app = express()
const cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
const session = require("express-session");
const FileStore = require("session-file-store")(session);
const upload = require("express-fileupload");
app.use(siofu.router)
app.use(upload());
console.log("Server Started!");
app.use(logger("dev"));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(
session({
resave: false,
secret: "hello",
saveUninitialized: true,
is_logged_in: false,
})
);
const indexRouter = require("./routes/index");
app.use("/", indexRouter);
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
module.exports = app;
如果你有任何问题,或可以给我任何提示,请做我只有大约5个月进入我的编码职业,所以我仍然有很多东西要学习 首先,这部分代码在后端,后端没有文档或窗口。这意味着document.getElementById在这里不起作用
io.on('connection', function (socket) {
const uploader = new siofu(socket);
uploader.prompt(document.getElementById("InputAddon"))
uploader.listen(socket)
socket.on('sent message', function (msg) {
console.log('message' + ' : ' + JSON.stringify(msg))
socket.broadcast.emit('message', msg);
})
})
然后没有上传文件位置/dir被定义
你可以看到这个例子
快速文件上传
app.use(fileUpload({
useTempFiles : true,
tempFileDir : '/tmp/'
}));
socketio文件上传
io.on("connection", function(socket){
var uploader = new siofu();
uploader.dir = "/path/to/save/uploads"; ***//upload directory***
uploader.listen(socket);
});
所以我建议你通过下面提到的链接更新你的代码
为了从前端上传文件,您需要做的是在useEffect inside ChatBox组件中在前端创建socket file upload的实例 此外,您还需要创建一个虚拟的隐藏输入,当单击上载按钮时,您可以在该输入上模拟单击,还需要创建一个可以监听的输入 需要添加的小代码段
const fileRef = useRef(null);
useEffect(() => {
const siofu = new SocketIOFileUpload(state.socket);
// call listen on input and pass the hidden input ref
siofu.listenOnInput(fileRef.current);
}, [state.socket])
const InputAddon = () => {
// Trigger click on fileRef input
fileRef.current.click();
}
带输入的完整组件代码
import SocketIOFileUpload from 'socketio-file-upload';
const ChatBox = () => {
const [textValue, changeTextValue] = React.useState('');
const { state, dispatch } = React.useContext(CTX);
console.log(state.user)
React.useEffect(() => {
console.log(state.user)
state.socket.on('message', function (msg) {
console.log("chat message recieved")
dispatch('RECEIVE_MESSAGE', msg);
})
}, [])
const onKeyPressHandler = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
console.log("PRESSED")
state.socket.emit('sent message', { from: state.user, msg: textValue, channel: state.selectedChannel });
dispatch('RECEIVE_MESSAGE', { from: state.user, msg: textValue, channel: state.selectedChannel });
changeTextValue('')
}
}
const onChangeHandler = e => {
changeTextValue(e.target.value);
}
const fileRef = useRef(null);
useEffect(() => {
const siofu = new SocketIOFileUpload(state.socket);
// call listen on input and pass the hidden input ref
siofu.listenOnInput(fileRef.current);
}, [state.socket])
const InputAddon = () => {
// Trigger click on fileRef input
fileRef.current.click();
}
return (
<Layout>
<Sidebar />
<Wrapper>
<InnerBoxWrapper>
<InnerBox>
<UserMessage />
<InputWrapper>
<InputAddons id="InputAddon">
<FontAwesomeIcon icon={faPlus} onClick={InputAddon}></FontAwesomeIcon>
</InputAddons>
<input
ref={fileRef}
label="file-picker"
type="file"
style={{display: 'none'}}
/>
<input
label="Send a chat"
onChange={onChangeHandler}
value={textValue}
onKeyPress={onKeyPressHandler}
/>
</InputWrapper>
</InnerBox>
</InnerBoxWrapper>
</Wrapper>
</Layout>
)
}
app.js
const siofu = require('socketio-file-upload')
const app = express()
const cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
const session = require("express-session");
const FileStore = require("session-file-store")(session);
app.use(siofu.router)
console.log("Server Started!");
app.use(logger("dev"));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(
session({
resave: false,
secret: "hello",
saveUninitialized: true,
is_logged_in: false,
})
);
const indexRouter = require("./routes/index");
app.use("/", indexRouter);
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
从目标位置识别图像文件,然后使用
public static byte[] readBytesFromFile(File file) throws IOException
{
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE)
{
is.close();
throw new IOException("Could not completely read file " + file.getName() + " as it is too long (" + length + " bytes, max supported " + Integer.MAX_VALUE + ")");
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0)
{
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length)
{
is.close();
throw new IOException("Could not completely read file " +file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public static byte[]readBytesFromFile(文件文件)引发IOException
{
InputStream is=新文件InputStream(文件);
//获取文件的大小
long length=file.length();
//不能使用长类型创建数组。
//它必须是int类型。
//在转换为int类型之前,请检查
//以确保文件不大于Integer.MAX_值。
if(长度>整数最大值)
{
is.close();
抛出新IOException(“无法完全读取文件”+file.getName()+,因为它太长(“+length+”字节,支持的最大值“+Integer.max_VALUE+”));
}
//创建字节数组以保存数据
字节[]字节=新字节[(int)长度];
//读入字节
整数偏移=0;
int numRead=0;
而(偏移量=0)
{
偏移量+=numRead;
}
//确保已读入所有字节
if(偏移量<字节长度)
{
is.close();
抛出新IOException(“无法完全读取文件”+file.getName());
}
//关闭输入流并返回字节
is.close();
返回字节;
}
将图像数据存储到字节数组中
然后,提及你的目的地并申请
它将运行
import SocketIOFileUpload from 'socketio-file-upload';
const ChatBox = () => {
const [textValue, changeTextValue] = React.useState('');
const { state, dispatch } = React.useContext(CTX);
console.log(state.user)
React.useEffect(() => {
console.log(state.user)
state.socket.on('message', function (msg) {
console.log("chat message recieved")
dispatch('RECEIVE_MESSAGE', msg);
})
}, [])
const onKeyPressHandler = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
console.log("PRESSED")
state.socket.emit('sent message', { from: state.user, msg: textValue, channel: state.selectedChannel });
dispatch('RECEIVE_MESSAGE', { from: state.user, msg: textValue, channel: state.selectedChannel });
changeTextValue('')
}
}
const onChangeHandler = e => {
changeTextValue(e.target.value);
}
const fileRef = useRef(null);
useEffect(() => {
const siofu = new SocketIOFileUpload(state.socket);
// call listen on input and pass the hidden input ref
siofu.listenOnInput(fileRef.current);
}, [state.socket])
const InputAddon = () => {
// Trigger click on fileRef input
fileRef.current.click();
}
return (
<Layout>
<Sidebar />
<Wrapper>
<InnerBoxWrapper>
<InnerBox>
<UserMessage />
<InputWrapper>
<InputAddons id="InputAddon">
<FontAwesomeIcon icon={faPlus} onClick={InputAddon}></FontAwesomeIcon>
</InputAddons>
<input
ref={fileRef}
label="file-picker"
type="file"
style={{display: 'none'}}
/>
<input
label="Send a chat"
onChange={onChangeHandler}
value={textValue}
onKeyPress={onKeyPressHandler}
/>
</InputWrapper>
</InnerBox>
</InnerBoxWrapper>
</Wrapper>
</Layout>
)
}
var app = require('../app');
var debug = require('debug')('cryptidbackend:server');
const socketio = require('socket.io');
/**
* Get port from environment and store in Express.
*/
app.listen(3001, function () {
console.log('listening on 3001')
})
var io = socketio.listen(app);
// Socket.io
io.sockets.on('connection', function (socket) {
const uploader = new siofu(socket);
uploader.listen(socket)
uploader.dir = "/srv/uploads";
uploader.listen(socket);
// Do something when a file is saved:
uploader.on("saved", function(event){
console.log(event.file);
});
// Error handler:
uploader.on("error", function(event){
console.log("Error from uploader", event);
});
})
const siofu = require('socketio-file-upload')
const app = express()
const cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
const session = require("express-session");
const FileStore = require("session-file-store")(session);
app.use(siofu.router)
console.log("Server Started!");
app.use(logger("dev"));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(
session({
resave: false,
secret: "hello",
saveUninitialized: true,
is_logged_in: false,
})
);
const indexRouter = require("./routes/index");
app.use("/", indexRouter);
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
public static byte[] readBytesFromFile(File file) throws IOException
{
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE)
{
is.close();
throw new IOException("Could not completely read file " + file.getName() + " as it is too long (" + length + " bytes, max supported " + Integer.MAX_VALUE + ")");
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0)
{
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length)
{
is.close();
throw new IOException("Could not completely read file " +file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}