jquery - 如何将文件保存到映射路径 apicontroller asp .net mvc4

标签 jquery asp.net asp.net-mvc asp.net-mvc-4 jquery-file-upload

所以我正在开发一个项目并上传一个带有进度条的文件。我有进度条工作。我的文件分段进入我的 Controller ,我需要将其保存到服务器。这是我的 apicontroller 代码

namespace MvcMovie.Controllers.WebApi
{
public class UploadController : ApiController
{
    // Enable both Get and Post so that our jquery call can send data, and get a status
    [HttpGet]
    [HttpPost]
    public HttpResponseMessage Upload()
    {
        // Get a reference to the file that our jQuery sent.  Even with multiple files, they will all be their own request and be the 0 index
        HttpPostedFile file = HttpContext.Current.Request.Files[0];
        // do something with the file in this space 
        // {....}
        // end of file doing

        var filelenght = file.ContentLength;
        // Now we need to wire up a response so that the calling script understands what happened
        HttpContext.Current.Response.ContentType = "text/plain";
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        var result = new { name = file.FileName };

        HttpContext.Current.Response.Write(serializer.Serialize(result));
        HttpContext.Current.Response.StatusCode = 200;

        // For compatibility with IE's "done" event we need to return a result as well as setting the context.response
        return new HttpResponseMessage(HttpStatusCode.OK);
    }

}
}

但我不确定如何将文件保存到服务器上,因为它是分段的。在另一个项目中,我使用了普通 Controller ,只是使用了这个:

    [Authorize]
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        var username = WebSecurity.CurrentUserName;

        if (file.ContentLength > 0)
        {

            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads/" + username), fileName);
            file.SaveAs(path);
        }

        return RedirectToAction("Index");
    }

但是当我尝试在我的 apicontroller Server.MapPath 中实现该代码时,它不起作用。所以我想我的问题有两部分:如何将上传的文件保存在 apiwebcontroller 中以及如何在分段时保存它?

这是我认为的 javascript,如果你想看的话:

    $(function () {
        $('#fileupload').fileupload({
            dataType: "json",
            url: "/api/upload",
            limitConcurrentUploads: 1,
            sequentialUploads: true,
            progressInterval: 100,
            maxChunkSize: 10000,
            add: function (e, data) {
                $('#filelistholder').removeClass('hide');
                data.context = $('<div />').text(data.files[0].name).appendTo('#filelistholder');
                $('</div><div class="progress"><div class="bar" style="width:0%"></div></div>').appendTo(data.context);
                $('#btnUploadAll').click(function () {
                    data.submit();
                });
            },
            done: function (e, data) {
                data.context.text(data.files[0].name + '... Completed');
                $('</div><div class="progress"><div class="bar" style="width:100%"></div></div>').appendTo(data.context);
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#overallbar').css('width', progress + '%');
            },
            progress: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                data.context.find('.bar').css('width', progress + '%');
            }
        });
    });

最佳答案

        if (File.Exists(HttpContext.Current.Server.MapPath("~/App_Data/uploads/test/" + file.FileName)))
        {
            Stream input = file.InputStream;
            FileStream output = new FileStream(HttpContext.Current.Server.MapPath("~/App_Data/uploads/test/" + file.FileName), FileMode.Append);
            byte[] buffer = new byte[8 * 1024];
            int len;
            while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, len);
            }
            input.Close();
            output.Close();
        }
        else
        {
            file.SaveAs(HttpContext.Current.Server.MapPath("~/App_Data/uploads/test/" + file.FileName));
        }

这就是我发现最终有效的方法。当您使用 API Controller 时,它能够将路径映射到您必须使用的服务器。 HttpContext.Current.Server.MapPath。然后我所要做的就是创建一个文件并将文件流附加到其中。

关于jquery - 如何将文件保存到映射路径 apicontroller asp .net mvc4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18412608/

相关文章:

javascript - jquery在asp.net中选择下拉列表控件

html - 使用 CSS 媒体查询

c# - ASP.NET CORE 文件上传问题

c# - .NET 中的单元测试和 UI 测试

javascript - 停止代码直到 AJAX 调用在 $.each 循环内完成

javascript - 使用 Underscore.js 在嵌套集合中查找对象

c# - 如何一次迭代3个数组

asp.net-mvc - 最新版本上的 Cassette NullReferenceException

javascript - 更改 Google map 的 RichMarker 光标

javascript - 防止在内联编辑模式下编辑特定可编辑行的单元格