我使用以下代码将文件上传到服务器,但该文件未上传.

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);
                }
            }
        });
    }
}

该操作命中,但该文件未上传.

解决方法

而不是提交按钮,你可以尝试使用普通按钮 –
<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,processData: false
            });
        });
    });
</script>

控制器动作 –

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的更多相关文章

  1. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. 在IOS9中的Cordova应用程序使用JQuery / Javascript的window.history问题

    在两个测试用例中唯一改变的是Cordova.js.解决方法我看到这是几个星期前,但我会发布这个,以防其他人遇到它.听起来它可能与iOS9中的哈希更改生成的导航事件有关.如果是这样,可以将其添加到index.html以禁用哈希侦听:

  3. iOS 5上的jQuery事件

    解决方法在Apple开发论坛上由一个人回答:我需要在将元素添加到DOM之后才绑定(),如下所示:

  4. android – Phonegap本地构建 – jquery ajax错误:readystate 0 responsetext status 0 statustext error

    解决方法您是否在索引文件中包含了内容安全元标记?

  5. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  6. 设置焦点到输入框和显示Android键盘使用jquery手机在pageshow

    我正在设置焦点到输入框,并显示Android键盘使用jquery手机网页显示.我从Web上尝试过很多选项.但是没有一个在模拟器和移动设备中都能按预期工作.这是代码:查找屏幕截图以供参考请咨询…解决方法对我有用的解决方案

  7. android – 如何在焦点()上以编程方式隐藏jquery mobile中的键盘

    我想在Focus()上隐藏键盘,但是当$(“.ui-input-text”).focus();它会自动打开键盘.我只是想隐藏在特定的屏幕上,我用document.activeElement.blur()测试;但它也没有关注()输入.解决方法提交表单时,iOS键盘可能不会自动关闭.这是一个非常实用的问题,因为不应要求用户手动关闭键盘,否则他们不会期望需要这样做.可以通过调用document.acti

  8. jquery ajaxfileupload异步上传插件

    这篇文章主要为大家详细介绍了jquery ajaxfileupload异步上传插件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  9. jQuery实现简单的抽奖游戏

    这篇文章主要为大家详细介绍了jQuery实现简单的抽奖游戏,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. jQuery的Cookie封装,与PHP交互的简单实现

    下面小编就为大家带来一篇jQuery的Cookie封装,与PHP交互的简单实现。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

随机推荐

  1. jquery-plugins – 是否可以使用猫头鹰旋转木马实现循环/无限轮播?

    我正在使用猫头鹰旋转木马,它的工作完美,除了它不支持循环/无限滚动.我没有搜索google和stackoverflow的想法,没有运气.有没有人在猫头鹰旋转木马上实现圆形/无限滚动?

  2. jQuery动态输入字段焦点

    我想使用以下jQuery向我的页面动态添加一个输入字段:在这样做之后,我希望输入字段具有闪烁的文本光标的焦点,所以我想在创建后立即输入.有人可以告诉我我该怎么办?

  3. jquery – 为什么$(window).height()这样错了?

    我试图获取当前浏览器的视口高度,使用但我得到的价值观太低了.当视口高度高达850px时,我从height()获取大约350或400像素的值.这是怎么回事?

  4. jquery – 如果在此div之外和其他draggables内部(使用无效和有效的还原选项),则可拖动恢复

    例如这样但是由于明显的原因,这不行.我可以说这个吗?

  5. 创建一个jQueryUI 1.8按钮菜单

    现在jQueryUI1.8已经出来了,我正在浏览更新,并且遇到了新的Buttonwidget,特别是SplitButtonwithadropdown的演示之一.这个演示似乎表明Buttonwidget可以在这里创建一个下拉菜单.作为讨论的问题,我想知道使用这个新的Button小部件来创建一个下拉菜单有什么方法.干杯.解决方法您必须在按钮下方列出一个列表,方式类似于此处为自动完成提供的演示:http

  6. 灰色divs使用JQuery

    我试图使用这个代码:为了淡出一大堆名为MySelectorDiv的div,唯一的是,它只会淡出第一个而不是所有的div,为什么呢?

  7. 使用jQuery动态插入到列表中

    我有两个订单列表在彼此旁边.当我从一个列表中选出一个节点时,我想按照字母顺序插入到另一个列表中.抓住的是我想要把一个元素放在另一个列表中,而不刷新整个列表.奇怪的是,当我插入到右边的列表中,它工作正常,但是当我插入到左边的列表中时,顺序永远不会出来.我也尝试将所有内容读入数组,并将其排序在一起,以防止children()方法没有按照显示顺序返回任何东西,但是我仍然得到相同的结果.这是我的jQuer

  8. 没有回应MediaWiki API使用jQuery

    我试图从维基百科获取一些内容作为JSON:但我没有回应.如果我粘贴到浏览器的地址栏,就像我得到预期的内容.怎么了?解决方法您需要通过添加&callback=?来触发具有$.getJSON()的JSONP行为?在querystring上,像这样:Youcantestithere.没有使用JSONP,你正在击中same-originpolicy,阻止XmlHttpRequest获取任何数据.

  9. jQuery Ajax请求每30秒

    我有这段代码,但是有些人在我的网站上的值可能会改变.我需要每30秒钟更新一次#financediv.这可以做吗解决方法您可以将代码放在单独的函数中,如下所示:然后每30秒建立一个定时器调用该函数:祝你好运!总结以上是DEVMAX为你收集整理的jQueryAjax请求每30秒全部内容。如果觉得DEVMAX网站内容还不错,欢迎将DEVMAX网站推荐给好友。

  10. jquery – keypress事件在IE和Chrome中不工作,但在FF工作

    任何想法为什么会这样发生?我通常认为Chrome会更加宽容代码?这是我的按键键.我错过了什么吗?右图();和leftimage();是应该工作的功能,因为我在其他地方使用这些功能谢谢您的帮助!

返回
顶部