代码之家  ›  专栏  ›  技术社区  ›  Grahame A

需要帮助调试基于XHR的Ajax图像上传吗ASP.NETMVC2型

  •  9
  • Grahame A  · 技术社区  · 16 年前

    我正在尝试使用从中找到的脚本 http://valums.com/ajax-upload/

    我的控制器如下

    using System;
    using System.IO;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.Hosting;
    using System.Web.Mvc;
    using MHNHub.Areas.ViewModels;
    using MHNHub.Models;
    using MHNHub.ViewModels;
    
    namespace MHNHub.Areas.Admin.Controllers
    {
        [Authorize(Roles = "Administrator")]
        public class ImageController : Controller
        {
    
            private MHNHubEntities _entities = new MHNHubEntities();
    
            //
            // GET: /Image/
            [AcceptVerbs(HttpVerbs.Get)]
            public ActionResult ImageUploader()
            {
                var viewModel = new ImageViewModel()
                {
                    Image = new Image()
                };
    
                return PartialView(viewModel);
            }
    
            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult ImageUploader(Image image)
            {
                try
                {
                    _entities.Images.AddObject(image);
                    _entities.SaveChanges();
    
                    return RedirectToAction("Index", "Product");
                }
                catch (Exception ex)
                {
                    var viewModel = new ImageViewModel()
                                    {
                                        Image = image,
                                        HasError = true,
                                        ErrorMessage = ex.Message
                                    };
                    return PartialView(viewModel);
    
                }
            }
    
            private string _uploadsFolder = HostingEnvironment.MapPath("~/App_Data/Files");
    
            public Guid Upload(HttpPostedFileBase fileBase)
            {
                var identifier = Guid.NewGuid();
                fileBase.SaveAs(GetDiskLocation(identifier));
                return identifier;
            }
    
            private string GetDiskLocation(Guid identifier)
            {
                return Path.Combine(_uploadsFolder, identifier.ToString());
            }
    
        }
    
    }
    

    我有这样的偏颇观点

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MHNHub.ViewModels.ImageViewModel>" %>
    
    <script type="text/javascript">
        $(function () {
            $("#imagedialog").dialog({
                bgiframe: true,
                height: 170,
                width: 430,
                modal: true,
                autoOpen: false,
                resizable: true
            })
        });
    
        $(document).ready(function createUploader() {
            var uploader = new qq.FileUploader({
                element: document.getElementById('fileuploader'),
                action: '/Image/Upload/',
                name: 'name'
            });
    
        });
    
    </script>    
    
    <div id="imagedialog" title="Upload Image">
    
                    <div id="fileuploader">
    
                    </div>
                    <h6>Drag and drop files supported in Firefox and Google Chrome with javascript enabled.</h6> 
                        <noscript>
                             <form action="/image/upload" enctype="multipart/form-data" method="post">
                                Select a file: <input type="file" name="photo" id="photo" />   
    
                                <input type="submit" value="Upload" name="submit"/>
                            </form>
                        </noscript>
    
    
    </div>
    
    <div class="editor-field">
        <img src="<%: Model.Image.FileName %>" />
        <%: Html.TextBoxFor(model => model.Image.FileName) %>
        <%: Html.ValidationMessageFor(model => model.Image.FileName)%>
        <a href="#" onclick="jQuery('#imagedialog').dialog('open'); return false">Upload Image</a>
    </div>
    

    编辑

    所以我发现使用firebug发送XmlHttpRequest。如何在上传操作中处理此问题?

    1 回复  |  直到 16 年前
        1
  •  9
  •   Darin Dimitrov    16 年前

    在控制器操作中获取空参数的原因是因为此插件不发送 multipart/form-data 请求服务器。相反,它发送 application/octet-stream content-type请求头,它将文件内容直接写入请求流,并附加一个参数 ?qqfile 指向包含文件名的URL。因此,如果您要在控制器上检索此信息,则需要直接读取流:

    [HttpPost]
    public ActionResult Upload(string qqfile)
    {
        using (var reader = new BinaryReader(Request.InputStream))
        {
            // This will contain the uploaded file data and the qqfile the name
            byte[] file = reader.ReadBytes((int)Request.InputStream.Length);
        }
        return View();
    }
    

    如果你选择了多个文件,插件只需发送多个请求到服务器,这样就可以了。

    如果你想处理比 int.MaxValue

    using (var outputStream = File.Create(qqfile))
    {
        const int chunkSize = 2 * 1024; // 2KB
        byte[] buffer = new byte[chunkSize];
        int bytesRead;
        while ((bytesRead = Request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            outputStream.Write(buffer, 0, bytesRead);
        }
    }
    

    createUploader 函数名来自 document.ready . 它应该是一个匿名函数。你甚至可以把它和 $(function() { ... }); 您已经需要设置模式对话框了。