无法从 JS 或 Web url 访问静态文件夹

问题描述 投票:0回答:1

:) 我正在努力将我的 GUI 应用程序转换为使用 Flask 作为后端、HTML、JS 和 CSS 作为前端的 Webapp。 (我不是 FS 开发者或类似的东西,但我正在学习)

当我从连接的表中选择一个远程站时,我可以抓取屏幕截图并将其保存在本地“static/images/{Hostname}”下(在这种情况下就是:“static/images/SANDBOX”)。 我正在尝试获取位于内部的文件列表,以便我可以在位于详细信息容器中的图像滑块中显示图像,但我收到 404 not found 错误。

当我尝试加载http://127.0.0.1:8000/static我得到404。与http://127.0.0.1:8000/static/images.

相同

我该如何解决这个问题? JS:

const rows = document.querySelectorAll(".row-data");
rows.forEach((row) => {
    row.addEventListener("click", () => {
        rows.forEach((row) => {
            row.classList.remove("selected");
        });
        row.classList.add("selected");

        const selectedRowData = {
            id: row.cells[0].innerText,
            ip_address: row.cells[1].innerText,
            hostname: row.cells[2].innerText,
            logged_user: row.cells[3].innerText,
            boot_time: row.cells[4].innerText,
            connection_time: row.cells[5].innerText
        };

        // Check if hostname is not empty
        if (selectedRowData.hostname.trim() !== '') {
            // Get the directory name
            const directoryName = selectedRowData.hostname.trim();

            // Look for a directory with the same name under static/images
            fetch(`/get_images?directory=static/images/${directoryName}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
                .then(response => response.json())
                .then(data => {
                    console.log('Received response from Flask backend:', data);
                    // Show the images in the slider
                    const sliderHtml = getSliderHtml(data.images);
                    $('#slider-container').html(sliderHtml);
                })
                .catch(error => {
                    console.error('Error while getting images:', error);
                });
        }

        // Send the selected row data to the Flask backend
        fetch('/shell_data', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(selectedRowData)
        })
        .then(response => response.json())
        .then(data => {
            console.log('Received response from Flask backend:', data);
        })
        .catch(error => {
            console.error('Error while sending selected row data to Flask backend:', error);
        });
    });
});

// Helper function to generate HTML for the slider
function getSliderHtml(images) {
    let sliderHtml = '';
    if (images && images.length > 0) {
        sliderHtml += '<div class="slider">';
        images.forEach(function(image) {
            sliderHtml += '<div class="slide">';
            sliderHtml += '<img src="/static/images/' + image.path + '">';
            sliderHtml += '</div>';
        });
        sliderHtml += '</div>';
    } else {
        sliderHtml += '<p>No images found.</p>';
    }
    return sliderHtml;
}

烧瓶后端

class Backend:
    def __init__(self):
        self.app = Flask(__name__)
        self.sio = SocketIO(self.app)
        self.commands = Commands()
        self.images = {}
        self.app.route('/static/<path:path>')(self.serve_static)
        self.app.errorhandler(404)(self.page_not_found)

        self.sio.event('event')(self.on_event)
        self.sio.event('connect')(self.handle_connect)

        self.app.route('/')(self.index)
        self.app.route('/get_images', methods=['GET'])

        self.app.route('/controller', methods=['POST'])(self.send_message)
        self.app.route('/shell_data', methods=['POST'])(self.shell_data)

    def serve_static(self, path):
        return send_from_directory('static', path)

    def on_event(self, data):
        pass

    def handle_connect(self):
        pass

    def page_not_found(self, error):
        return jsonify({'error': 'Directory not found'}), 404

    def get_images(self):
        directory = request.args.get('directory')
        images = []

        # Check if the directory exists
        if os.path.isdir(directory):
            for filename in os.listdir(directory):
                if filename.endswith('.jpg'):
                    images.append({'path': os.path.join(directory, filename)})

        # Return images as JSON response
        return jsonify({'images': images})

    def shell_data(self):
        global shell_target
        selected_row_data = request.get_json()
        if isinstance(shell_target, list) and Backend().images:
            shell_target = []

        for endpoint in server.endpoints:
            if endpoint.ip == selected_row_data['ip_address']:
                shell_target = endpoint.conn
                endpoint_ident = endpoint.ident
                return jsonify({'message': 'Selected row data received and saved successfully'})

        return jsonify({'message': 'No endpoint found for the selected row data.'})
    

HTML

<div class="content">
            <h1>Connected Stations</h1>
            <table>
                <thead>
                    <tr>
                        <th>Client MAC</th>
                        <th>IP Address</th>
                        <th>Hostname</th>
                        <th>Logged User</th>
                        <th>Boot Time</th>
                        <th>Client Version</th>
                    </tr>
                </thead>
                <tbody>
                    {% for endpoint in endpoints %}
                    <tr class="row-data" data-id="{{ endpoint.client_mac }}" data-ip="{{ endpoint.ip }}" data-hostname="{{ endpoint.ident }}" data-user="{{ endpoint.user }}" data-boot="{{ endpoint.boot_time }}" data-connection="{{ endpoint.connection_time }}">
                        <td>{{ endpoint.client_mac }}</td>
                        <td>{{ endpoint.ip }}</td>
                        <td>{{ endpoint.ident }}</td>
                        <td>{{ endpoint.user }}</td>
                        <td>{{ endpoint.boot_time }}</td>
                        <td>{{ endpoint.client_version }}</td>

                    </tr>
                     {% endfor %}
                     {% if not endpoints %}
                    <script>
                        $(document).ready(function() {
                        $('table tr').click(function() {
                            var sliderHtml = '<div class="slider">';
                            var images = data.images;
                            if (images && images.length > 0) {
                                images.forEach(function(image) {
                                    sliderHtml += '<div class="slide">';
                                    sliderHtml += '<img src="/static/images/' + image.path + '">';
                                    sliderHtml += '</div>';
                                });
                            } else {
                                sliderHtml += '<div class="slide">';
                                sliderHtml += '<p>No images found.</p>';
                                sliderHtml += '</div>';
                            }
                            sliderHtml += '</div>';
                            $('#slider-container').html(sliderHtml);
                        });
                    </script>
                    <tr>
                        <td colspan="6">No endpoints found.</td>
                    </tr>
                    {% endif %}
                </tbody>
            </table>
        </div>

CSS

.box {
    background-color: #f2f2f2; /* light grey */
    margin-bottom: 10px;
    border-radius: 5px;
}

.small-box {
    padding: 5px;
    width: 300px;
    height: 100px;
}

.slider {
    width: 100%;
    display: flex;
    position: relative;
    overflow: hidden;
    scroll-snap-type: x mandatory;
    scroll-behavior: smooth;
}
.slider::-webkit-scrollbar {
    display: none;
}
.slider__image {
    flex: 1 0 auto;
    width: 100%;
    scroll-snap-align: start;
    cursor: pointer;
}
.slider__image:hover {
    opacity: 0.7;
}
.slider__image--expanded {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
    background: rgba(0, 0, 0, 0.9);
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}
.slider__image--expanded img {
    max-width: 90%;
    max-height: 90%;
    object-fit: contain;
}

如果您需要更多信息,请告诉我。 谢谢! :)

Google、ChatGPT 和搜索论坛。 chatGPT 给出了一些答案,这些答案填充了一些结果,但它们离我的目标还很短。

javascript python html flask flask-socketio
1个回答
-2
投票

企业识别号码 (BIN) 详细信息 实体名称:Noore Alam (Shåhårìýå) 所有权类型:独资 贸易品牌名称: KASBA 数码中心 & PHOTOSTAT e-TIN : 170140610786 VAu200cu200cT BIN : 004824206-0605 注册:注册主要经济活动领域零售/批发贸易

发行日期:07/07/2022 生效日期:07/2022 地址:Holding-82, Kasbs Porosova,Mohila College Road Sonali Bank;卡斯巴 PS; Brahmanbaria-3460;孟加拉国 手机:+880 1930893904 ,,

+880 1814976727

邮箱:[email protected] [email protected]

© www.soinside.com 2019 - 2024. All rights reserved.