Настройка плагина загрузки с WebAPI, получение только текста "Выбрать файлы"

Я пытаюсь настроить плагин загрузки с WebAPI для загрузки нескольких файлов (на основе статьи " http://donnyvblog.blogspot.in/2009/05/using-jquery-plugin-uploadify-with.html").

Вот мой HTML-код:

 <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    <script type="text/javascript" src="/scripts/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="/uploadify/jquery.uploadify.min.js"></script>  
    <script type="text/javascript" src="/client/api scripts/products.js"></script>
    <link href="../Uploadify/uploadify.css" type="text/css" />
    <script type="text/javascript">
    $(document).ready(function () {
        // alert("Here");
        $("#fileInput").uploadify({
            uploader: "/uploadify/uploadify.swf",
            script: "/api/files/Upload",
            cancelImg: "/uploadify/cancel.png",
            auto: true,
            folder: "/uploads",
            onError: function (a, b, c, d) {
                if (d.status == 404)
                    alert("Could not find upload script. Use a path relative to: " + "<?= getcwd() ?>");
                else if (d.type === "HTTP")
                    alert("error " + d.type + ": " + d.status);
                else if (d.type === "File Size")
                    alert(c.name + " " + d.type + " Limit: " + Math.round(d.sizeLimit / 1024) + "KB");
                else
                    alert("error " + d.type + ": " + d.text);
            }
        });
    });
</script>
</head>
<body>
        <input type="file" name="fileInput" id="fileInput" />        
</body>
</html>

Вот мой контроллер:

public class FilesController : ApiController
{

    [HttpPost]
    public string Upload(HttpPostedFileBase FileData)
    {
        /*
        *
        * Do something with the FileData
        *
        */
        return "Upload OK!";
    }
}

Я настроил свой маршрут как:

            config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }

Но все, что я получаю, это текст "Выбрать файлы" - без кнопки ничего. Ни мой контроллер не вызывается, ни кнопка отображается. Что я здесь делаю?

1 ответ

Решение

Не использовать HttpPostedFileBase как его использовали в MVC. Для Web API вы можете сделать что-то вроде следующего:

public class UploadController : ApiController
{
    public async Task<HttpResponseMessage> PostFormData()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

}

Проверьте следующую статью для более подробной информации:
http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2

Другие вопросы по тегам