jklemmack
jklemmack

Reputation: 3636

Upload a file with ServiceStack ss-utils.js

I have a job application form as part of a site built on ServiceStack. I am attempting to use the included ss-utils.js to leverage built-in Fluent Validation, but my form doesn't post the user's file upload. Here's the relevant snippet of the form:

<form id="form-careerapplication" action="@(new CreateCareerApplication().ToPostUrl())" method="post">
<div class="error-summary"></div>

<div class="form-group">
    <label>
        Upload Resume
    </label>
    <input type="file" id="Resume" name="Resume" />
    <span class="help-block"></span>
</div>

<input type="hidden" name="Id" value="@Model.Id" />
<input type="submit" value="Submit Application" />
</form>

<div id="success" class="hidden">
Thank you for your application.
</div>

$("#form-careerapplication").bindForm({
    success: function (careerApplicationResponse) {
        $("#form-careerapplication").addClass("hidden");
        $("#success").removeClass("hidden");
    },
    ...

Is there something I'm missing in ss-utils.js? Or is there a way of overriding / supplementing the submit behavior to use FormData?

Upvotes: 1

Views: 260

Answers (2)

jklemmack
jklemmack

Reputation: 3636

Turned out I can use the beforeSend option as part of the configuration passed into bindForm to override the data being sent. Its a bit of a hack, but it worked and I keep the original ss-utils.js fluent validation!

$("#form-careerapplication").bindForm({
    success: function (careerApplicationResponse) {
        ....
    },
    error: function (error) {
        ....
    },
    contentType: false,
    processData: false,
    beforeSend: function (x, settings) {
        var fd = new FormData();
        // Tweaked library from https://github.com/kflorence/jquery-deserialize/blob/master/src/jquery.deserialize.js
        // Used to translate the serialized form data back into 
        // key-value pairs acceptable by `FormData`
        var data = $.fn.deserialize(settings.data);
        $.each(data, function (i, item) {
            fd.append(item.name, item.value);
        });

        var files = $('#form-careerapplication').find("input:file");
        $.each(files, function (i, file) {
            fd.append('file', file.files[0], file.files[0].name);
        });
        settings.data = fd;
    }
});

Upvotes: 1

mythz
mythz

Reputation: 143339

Uploading files via a HTML FORM requires a enctype="multipart/form-data", e.g:

<form id="form-careerapplication" action="@(new CreateCareerApplication().ToPostUrl())" 
     method="post" enctype="multipart/form-data">
...
</form>  

If you want to change support multiple file uploads or change the appearance of the UI Form I recommend the Fine Uploader, there's an example showing how to use Fine Uploader on the HTTP Benchmarks Example.

Whilst Imgur has a simple client HTML and Server example.

Upvotes: 1

Related Questions