我正在尝试将从 javacsript 输入表单上传的文件发送到我的 sftp 服务器。我已经将 React 应用程序和 NodeJS 服务器解耦,因此将文件作为 URL 读取并将其发送到服务器,然后服务器调用 ssh2-sftp-client 的 put 函数。问题是,当它尝试放置时,它不起作用并按应返回状态代码 500。我尝试直接将 inputFile 发送到服务器端,但它不会传递它,就像我在服务器中控制台记录传递的文件一样,它返回一个空数组:{}。我该如何解决这个问题?感谢您的帮助。
这是客户端:
async function handleDockerInput(e) {
const inputFile = e.target.files[0];
try {
const loginResponse = await authService.logIn(user);
console.log('Login Response: ', loginResponse);
if (inputFile) {
const reader = new FileReader();
reader.readAsDataURL(inputFile);
reader.onload = async (event) => {
const dataUrl = event.target.result;
const body = JSON.stringify({
connect: SFTPConfig,
filepath: dataUrl,
remoteFilePath: '/'
});
const response = await dockerService.putObject(body);
console.log(response);
};
} else {
alert('Please upload a file');
}
} catch (error) {
console.error('Failed to login: ', error);
}
}
这是 dokerService.putObect 函数:
async putObject(body) {
const response = await axios.post('/docker/upload', body);
return response;
}
这是调用的服务器端函数:
public async upload(req: Request, res: Response): Promise<void> {
const dataUrl = req.body.filepath;
const remoteFilePath: string = req.body.remoteFilePath;
const sftp = new Client();
const { host, port, username, password } = req.body.connect;
const sftpConfig: SftpConfig = {
host: host,
port: port,
username: username,
password: password,
};
try {
await sftp.connect(sftpConfig);
const pathExists = await sftp.stat(remoteFilePath);
if(pathExists) {
try {
await sftp.put(dataUrl, remoteFilePath);
console.log('File uploaded successfully');
res.status(200).send('File uploaded successfully'); // Example error handling
} catch (error) {
res.status(500).send('Error uploading file to SFTP here'); // Example error handling
}
} else {
console.log('Inserted path doesn\'t exist');
res.status(500).send('Inserted path doesn\'t exist'); // Example error handling
}
} catch (error) {
console.log(error, 'catch error');
res.status(500).send('Error uploading file to SFTP'); // Example error handling
} finally {
sftp.end(); // Ensure the connection is closed after operation
}
}
问题可能是您没有将正确的输入传递给
sftp.put
方法:
await sftp.put(dataUrl, remoteFilePath);
根据文档,它需要一个字符串、缓冲区或可读流:
put(src,remotePath,选项)==>字符串
src:字符串 |缓冲|可读流。用于将数据复制到远程服务器的数据源。
https://www.npmjs.com/package/ssh2-sftp-client#putsrc-remotepath-options--string
您向其传递的是一个 base64 字符串,这不是可接受的输入。
所以,尝试用Buffer将base64字符串转换为图像,然后传递。
试试这个:
// convert base64 to file
const base64ToBuffer = new Buffer.from(dataUrl.replace(/^data:image\/png;base64,/, ''), 'base64');
// pass buffer
await sftp.put(base64ToBuffer, remoteFilePath);