文件上传的Jquery的WebAPI [英] File upload Jquery WebApi

查看:252
本文介绍了文件上传的Jquery的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个下code上传文件到服务器,但该文件没有上传。

I used this following code to upload file to server, but the file is not uploaded.

HTML:

      <form id="upload">
        <div>
            <label for="myFile"></label>
            <div>
                <input type="file" id="myFile" />
            </div>
        </div>
        <button type="submit">Upload</button>
    </form>

的Javascript:

     // Hook into the form's submit event.
    $('#upload').submit(function () {

        // To keep things simple in this example, we'll
        // use the FormData XMLHttpRequest Level 2 object (which
        // requires modern browsers e.g. IE10+, Firefox 4+, Chrome 7+, Opera 12+ etc).
        var formData = new FormData();

        // We'll grab our file upload form element (there's only one, hence [0]).
        var opmlFile = $('#opmlFile')[0];

        // If this example we'll just grab the one file (and hope there's at least one).
        formData.append("opmlFile", opmlFile.files[0]);

        // Now we can send our upload!
        $.ajax({
            url: 'api/upload', // We'll send to our Web API UploadController
            data: formData, // Pass through our fancy form data

            // To prevent jQuery from trying to do clever things with our post which
            // will break our upload, we'll set the following to false
            cache: false,
            contentType: false,
            processData: false,

            // We're doing a post, obviously.
            type: 'POST',

            success: function () {
                // Success!
                alert('Woot!');
            }
        });

        // Returning false will prevent the event from
        // bubbling and re-posting the form (synchronously).
        return false;
    });

控制器如下:

         using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

class UploadController : ApiController
{
    public async void Post()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
        }

        // We'll store the uploaded files in an Uploads folder under the web app's App_Data special folder
        var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data/Uploads/"));

        // Once the files have been written out, we can then process them.
        await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
        {
            if (t.IsFaulted || t.IsCanceled)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }

            // Here we can iterate over each file that got uploaded.
            foreach (var fileData in t.Result.FileData)
            {
                // Some good things to do are to check the MIME type before we do the processing, e.g. for XML:
                if (fileData.Headers.ContentType.MediaType.Equals("text/xml", StringComparison.InvariantCultureIgnoreCase))
                {
                    // And this is how we can read the contents (note you would probably want to do this asychronously
                    // but let's try keep things simple for now).
                    string contents = File.ReadAllText(fileData.LocalFileName);
                }
            }
        });
    }
}

行动打击,但该文件没有上传。

The action hit, but the file is not uploaded.

推荐答案

而不是提交按钮,你可以尝试用普通的按钮 -

Instead of submit button can you try with normal button -

<form enctype="multipart/form-data">
    <label>
        Using JQuery
    </label>
    <input name="file" type="file" id="me" />
    <input type="button" id="Upload" value="Upload" />
</form>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('#Upload').click(function () {
            var formData = new FormData();
            var opmlFile = $('#me')[0];
            formData.append("opmlFile", opmlFile.files[0]);

            $.ajax({
                url: 'http://localhost:23133/api/file',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false
            });
        });
    });
</script>

控制器动作 -

Controller Action -

    public HttpResponseMessage Post()
    {
        HttpResponseMessage result = null;
        var httpRequest = HttpContext.Current.Request;

        // Check if files are available
        if (httpRequest.Files.Count > 0)
        {
            var files = new List<string>();

            // interate the files and save on the server
            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                postedFile.SaveAs(filePath);

                files.Add(filePath);
            }

            // return result
            result = Request.CreateResponse(HttpStatusCode.Created, files);
        }
        else
        {
            // return BadRequest (no file(s) available)
            result = Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        return result;
    }

输出 -

这篇关于文件上传的Jquery的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆