使用ServiceStack ss-utils.js上传文件

时间:2015-07-27 22:27:45

标签: servicestack

我有一份工作申请表,作为在ServiceStack上构建的网站的一部分。我正在尝试使用包含的ss-utils.js来利用内置的Fluent验证,但我的表单并未发布用户的文件上传。这是表格的相关摘要:

<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");
    },
    ...

ss-utils.js中是否遗漏了某些内容?或者有没有办法覆盖/补充submit行为以使用FormData

2 个答案:

答案 0 :(得分:1)

通过HTML FORM上传文件需要enctype="multipart/form-data",例如:

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

如果您想更改支持多个文件上传或更改UI表单的外观,我建议使用Fine Uploader,其中有一个示例说明如何use Fine Uploader on the HTTP Benchmarks Example

虽然Imgur有一个简单的client HTMLServer example

答案 1 :(得分:1)

原来我可以使用beforeSend选项作为传递到bindForm的配置的一部分来覆盖正在发送的数据。它有点像黑客,但它有效,我保持原来的ss-utils.js流畅的验证!

$("#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;
    }
});