File uploads

babongo edited this page Oct 4, 2012 · 2 revisions

File uploads

Follow the bootstrap procedure in the tutorial to setup a KLone-app.

We will create two files (but you can merge them if you really want to):

  • the first file upload.html contains just the HTML tags needed to the browser to display the file selection widget;
<!-- upload.html -->
<form method="post" enctype="multipart/form-data" action="filesubmit.kl1">
<b>Select the input file below:</b><p>
  <input type="file" name="input_file" value="">
  <input type="submit" name="submit">
  • the second file filesubmit.kl1 is the actual KLone script that extract the file information from the request object and displays its name and size.
<!-- filesubmit.kl1 -->
    char filename[U_FILENAME_MAX], client_filename[U_FILENAME_MAX];
    char mime_type[MIME_TYPE_BUFSZ];
    size_t file_sz;

    /* disable client side caching */

    if(!request_get_arg(request, "submit"))
        goto footer; /* error */

    /* get the uploaded file */
    if(request_get_uploaded_file(request, "input_file", 0, filename,
            client_filename, mime_type, &file_sz))
        goto footer; /* error */

    io_printf(out, "mime_type: %s <p>", mime_type);
    io_printf(out, "temporary filename: %s <p>", filename);
    io_printf(out, "client filename: %s <p>", client_filename);
    io_printf(out, "file size: %u <p>", file_sz);

    /* do something with the file... e.g.:
     * (void) u_copy(filename, "/tmp/uploaded_file");

The difference between the filename and client_filename params is that the former is the path to a temporary file stored on the server disk (something like /tmp/file134234) while the latter is the name of the file on the client machine (mypreciousfile.pdf).

Note that the input_file string in the request_get_uploaded_file() function call is the name of the INPUT tag in the above form; so if you want to add more the one file upload per page just add another INPUT tag with a different name and call request_get_uploaded_file() again with the proper name argument.

If, otherwise, you want to upload more then one file with the same INPUT name param you can use the idx argument of request_get_uploaded_file() to iterate over the list of uploads.