Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

write js code for sending that cratetes dropzone and send request with uploaded file and…

  1. User

    write js code for sending that cratetes dropzone and send request with uploaded file and choosen target languages to this endpoint @router.post("/multi-local-from-file") async def multi_local_from_file( data: UploadFile, target_lang_list: list[str] = LANGUAGE_LIST, source_lang: str = "en", ) -> StreamingResponse: """ Translates the arb file into several languages

    - **data**: arb file
    - **source_lang**: original language
    - **target_lang_list**: languages after translation
    """
    data_dict = get_dict_from_arb_file(data.file)
    
    tmpdir = tempfile.TemporaryDirectory()
    
    # target_lang_list = comma_str_to_list(target_lang_list)
    file_paths = multi_lang_translate(source_lang, target_lang_list, data_dict, tmpdir)
    zip_io = save_files_to_zip(file_paths)
    
    return StreamingResponse(
        iter([zip_io.getvalue()]),
        media_type="application/x-zip-compressed",
        headers={"Content-Disposition": f"attachment; filename=translated.zip"},
    ) I already wrote html <!-- Create the form and dropzone element -->
    
  2. Assistant

    // JS code for Dropzone initialization Dropzone.autoDiscover = false; $(document).ready(function() { // Initialize Dropzone var myDropzone = new Dropzone("#my-dropzone", { url: "/localization/multi-local-from-file", paramName: "data", maxFilesize: 2, acceptedFiles: ".arb", dictDefaultMessage: "Drag and drop an ARB file here or click to select one", dictFallbackMessage: "Your browser does not support drag and drop file uploads.", dictInvalidFileType: "Only ARB files are allowed.", dictFileTooBig: "The file is too big ({{filesize}}MiB). Maximum allowed size: {{maxFilesize}}MiB.", dictResponseError: "Server responded with {{statusCode}} code.", dictCancelUpload: "Cancel upload", dictUploadCanceled: "Upload canceled.", dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?", dictRemoveFile: "Remove file", dictMaxFilesExceeded: "You can't upload any more files.", addRemoveLinks: true, autoProcessQueue: false });

    // Send request on form submit
    $("#translate-btn").click(function(e) {
        e.preventDefault();
        myDropzone.processQueue();
    });
    
    // Download translated files
    $("#download-multiple").hide();
    myDropzone.on("success", function(file, response) {
        $("#download-multiple").show();
    });
    $("#download-multiple").click(function() {
        window.location.href = "/static/translated.zip";
    });
    

    });

    // JS code for sending selected languages along with the uploaded file function getSelectedLanguages() { var languages = []; ("#target_lang_list option:selected").each(function() { languages.push((this).val()); }); return languages; }

    myDropzone.on("sending", function(file, xhr, formData) { var targetLanguages = getSelectedLanguages(); formData.append("target_lang_list", targetLanguages); formData.append("source_lang", "en"); });

  3. User

    send me it once again

  4. Assistant

    Sure, here's the complete JS code for creating a Dropzone and sending a request with uploaded file and selected target languages:

    Dropzone.autoDiscover = false;
    $(document).ready(function() {
        // Initialize Dropzone
        var myDropzone = new Dropzone("#my-dropzone", {
            url: "/localization/multi-local-from-file",
            paramName: "data",
            maxFilesize: 2,
            acceptedFiles: ".arb",
            dictDefaultMessage: "Drag and drop an ARB file here or click to select one",
            dictFallbackMessage: "Your browser does not support drag and drop file uploads.",
            dictInvalidFileType: "Only ARB files are allowed.",
            dictFileTooBig: "The file is too big ({{filesize}}MiB). Maximum allowed size: {{maxFilesize}}MiB.",
            dictResponseError: "Server responded with {{statusCode}} code.",
            dictCancelUpload: "Cancel upload",
            dictUploadCanceled: "Upload canceled.",
            dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?",
            dictRemoveFile: "Remove file",
            dictMaxFilesExceeded: "You can't upload any more files.",
            addRemoveLinks: true,
            autoProcessQueue: false
        });
        
        // Send request on form submit
        $("#translate-btn").click(function(e) {
            e.preventDefault();
            myDropzone.processQueue();
        });
        
        // Download translated files
        $("#download-multiple").hide();
        myDropzone.on("success", function(file, response) {
            $("#download-multiple").show();
        });
        $("#download-multiple").click(function() {
            window.location.href = "/static/translated.zip";
        });
    });
    
    // Get selected target languages
    function getSelectedLanguages() {
        var languages = [];
        $("#target_lang_list option:selected").each(function() {
            languages.push($(this).val());
        });
        return languages;
    }
    
    // Send selected target languages along with the uploaded file
    myDropzone.on("sending", function(file, xhr, formData) {
        var targetLanguages = getSelectedLanguages();
        formData.append("target_lang_list", targetLanguages);
        formData.append("source_lang", "en");
    });
    

    Remember to include this code in your HTML file, preferably at the bottom, after the </form> tag. Also, don't forget to import the necessary libraries and frameworks (jQuery, Dropzone, etc.) in your HTML file.

  5. User

    why i get an error on backend when drop file to dropzone. backend look like this @router.post("/multi-local-from-file") async def multi_local_from_file( data: UploadFile, target_lang_list: list[str] = LANGUAGE_LIST, source_lang: str = "en", ) -> StreamingResponse: """ Translates the arb file into several languages

    - **data**: arb file
    - **source_lang**: original language
    - **target_lang_list**: languages after translation
    """
    data_dict = get_dict_from_arb_file(data.file)
    
    tmpdir = tempfile.TemporaryDirectory()
    
    # target_lang_list = comma_str_to_list(target_lang_list)
    file_paths = multi_lang_translate(source_lang, target_lang_list, data_dict, tmpdir)
    zip_io = save_files_to_zip(file_paths)
    
    return StreamingResponse(
        iter([zip_io.getvalue()]),
        media_type="application/x-zip-compressed",
        headers={"Content-Disposition": f"attachment; filename=translated.zip"},
    ) and frontend <div class="form-group">
                    <!-- Create the dropzone element -->
                    <label for="my-dropzone">Choose an ARB file</label>
                    <div class="dropzone disabled" id="my-dropzone"></div>
                </div>  <script type="text/javascript">
    Dropzone.autoDiscover = false;
    $(document).ready(function() {
        // Initialize the dropzone element
        $("#my-dropzone").dropzone({
            url: "/localization/multi-local-from-file",
            addRemoveLinks: true,
            paramName: "data",
            maxFiles: 1,
            maxFilesize: 3, // Maximum filesize in MB
            acceptedFiles: ".arb",
            dictDefaultMessage: "Drag and drop an ARB file here or click to select one",
            dictFallbackMessage: "Your browser does not support drag and drop file uploads.",
            dictInvalidFileType: "Only ARB files are allowed.",
            dictFileTooBig: "The file is too big 3 Mb. Maximum allowed size: 3 Mb.",
            dictResponseError: "Server responded with {{statusCode}} code.",
            dictCancelUpload: "Cancel upload",
            dictUploadCanceled: "Upload canceled.",
            dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?",
            dictRemoveFile: "Remove file",
            dictMaxFilesExceeded: "You can’t upload any more files.",
            }
        });
    });
    
  6. Assistant

    It's hard to say without more information, but a common reason for upload errors with Dropzone is that the server (i.e., your backend code) isn't configured to accept file uploads.

    First, make sure that you've added the file field to your form tag and set the method attribute to "POST". For example:

    <form action="/localization/multi-local-from-file" method="POST" enctype="multipart/form-data">
        ...
        <div class="form-group">
            <!-- Create the dropzone element -->
            <label for="my-dropzone">Choose an ARB file</label>
            <div class="dropzone disabled" id="my-dropzone"></div>
        </div>
        ...
    </form>
    

    Make sure that your backend code is able to receive the uploaded file. You can test this by adding print statements to your code to debug the issue, like this:

    @router.post("/multi-local-from-file")
    async def multi_local_from_file(
            data: UploadFile,
            target_lang_list: list[str] = LANGUAGE_LIST,
            source_lang: str = "en",
    ) -> StreamingResponse:
        try:
            print('Receiving file...')
            data_dict = get_dict_from_arb_file(data.file)
            print('File received.')
            ...
        except Exception as e:
            print(f'Error: {e}')
    

    Also, make sure that you have permissions to write to the temporary directory where you save the translated files.

    If none of these steps help, please provide more details about the error message you're receiving and any relevant logs or stack traces, and I can try to help you further.

  7. User

    change this to a tag

  8. Assistant

    Sure, here's the <a> tag equivalent of the <form> tag:

    <a class="btn btn-secondary" id="new-btn" href="home">New</a>
    

    In the <a> tag, the href attribute is set to the URL of the target page, which is "home" in this case. When the user clicks on this link, the browser will navigate to the target page.