Someone has tried recently using wix to connect to a ftp server? I’ve tried using my
websites to connect to my server but I have got very inconsistent results, sometimes I’m
able to send the file to my server, sometimes it gets stuck and never uploads and
sometimes it works on the first try … idk it’s very inconsistent. I have not configured
anything else, just the js functions and the server info to connect. The function receives the content from the file, and the filename and directory. Here is my code
const ftp = require(‘ftp’);
const { Readable } = require(‘stream’);
export function uploadFileFTP(credentials, fileContent, remotePath) {
**return** **new** Promise((resolve, reject) => {
**const** client = **new** ftp();
**let** isSettled = **false**;
**const** finish = (err, info) => {
**if** (isSettled) **return**;
isSettled = **true**;
**if** (err) {
console.error('FTP transfer error:', err.message || err);
client.end();
**return** reject(err);
}
client.end();
resolve(info);
};
client.once('ready', () => {
console.log('Connected to FTP server');
// Convert content to Buffer (text or binary)
**const** buffer = Buffer.isBuffer(fileContent)
? fileContent
: Buffer.**from**(fileContent, 'utf8');
**const** contentStream = Readable.**from**(buffer);
**const** totalBytes = buffer.length;
console.log(\`Uploading to "${remotePath}" (${totalBytes} bytes)...\`);
// Split folder and file name
**const** lastSlash = remotePath.lastIndexOf("/");
**const** folder = lastSlash > 0 ? remotePath.slice(0, lastSlash) : "";
**const** fileName = lastSlash > 0 ? remotePath.slice(lastSlash + 1) : remotePath;
**const** upload = () => {
client.put(contentStream, remotePath, (err) => {
**if** (err) **return** finish(err);
console.log('File uploaded successfully');
finish(**null**, {
success: **true**,
bytesTransferred: totalBytes,
remotePath
});
});
};
**if** (folder) {
// Create folder if it doesn't exist
client.mkdir(folder, **true**, (err) => {
**if** (err) **return** finish(err);
upload();
});
} **else** {
upload();
}
});
client.once('error', (err) => finish(err));
client.once('end', () => {
**if** (!isSettled) {
finish(**new** Error('The FTP connection was closed before the transfer was completed.'));
}
});
// Connection configuration
**const** connectionConfig = {
...credentials,
connTimeout: 60000,
pasvTimeout: 60000,
keepalive: 30000
};
console.log('Connecting to FTP server...');
client.connect(connectionConfig);
});
}