jQuery 使用 jQuery 的 ajax 方法上传文件(无插件)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2591291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:50:39  来源:igfitidea点击:

jQuery upload file using jQuery's ajax method (without plugins)

jqueryasp.net-mvcajaxupload

提问by Daniil Harik

At moment I want to implement picture upload without using any plug-ins.

目前想实现不使用任何插件的图片上传。

My upload form looks like this

我的上传表单看起来像这样

<form action="/Member/UploadPicture" enctype="multipart/form-data" id="uploadform" method="post">
            <span>
                <div class="upload" id="imgUpl">
                    <h3>Upload profile picture</h3>
                    <div class="clear5"></div>
                    <input  type="file" name="file" id="file"  />
                    <button class="btn-bl"  id="upComplete"><span>Upload</span></button>
                </div>

            </span>
            </form>

And my jQuery code is:

我的 jQuery 代码是:

  $('#upComplete').click(function () {
            $('#up').hide();
            $('#upRes').show();

            var form = $("#uploadform");

            $.ajax({
                type: "POST",
                url: "/Member/UploadPicture",
                data: form.serialize(),
                success: function (data) {
                    alert(data);
                }
            });

            $.fancybox.close();
            return false;
        });

If I open firebug, I can see that ajax() method does simple form post (not multi-part) and POST content is empty

如果我打开 firebug,我可以看到 ajax() 方法执行简单的表单发布(不是多部分)并且 POST 内容为空

Is it possible to do files upload using jQuery ajax() method or should I do this in any other way?

是否可以使用 jQuery ajax() 方法上传文件,或者我应该以任何其他方式上传?

Thank You very much

非常感谢您

采纳答案by Darin Dimitrov

jQuery ajax does not support file uploads and implementing this manually might be cumbersome. I would suggest you looking at the jQuery formplugin.

jQuery ajax 不支持文件上传,手动实现可能很麻烦。我建议您查看 jQuery表单插件。

Of course you could always check out the source code of the plugin to see how it is implemented if you don't want to include it (it uses a hidden iFrame as files cannot be uploaded with AJAX) but why doing it if you could use it directly :-)

当然,如果您不想包含它(它使用隐藏的 iFrame,因为文件无法使用 AJAX 上传),您可以随时查看插件的源代码以了解它是如何实现的,但是如果您可以使用,为什么要这样做它直接:-)

Here's an example how your code might look like:

下面是您的代码的示例:

$(function() {
    $('#uploadform').ajaxForm();
});

also make the upload button a submit button:

还将上传按钮设为提交按钮:

<button class="btn-bl" id="upComplete" type="submit">
    <span>Upload</span>
</button>

回答by Anurag

AJAXor more appropriately XMLHttpRequestdoes not support file uploads yet. There are workarounds such as uploading through an <iframe>, but its rather cumbersome. Your time will be better spent in building your applications rather than reinventing these solutions.

AJAX或更恰当地说XMLHttpRequest,尚不支持文件上传。有一些解决方法,例如通过 上传<iframe>,但它相当麻烦。您将更好地将时间花在构建应用程序上,而不是重新发明这些解决方案。

But if you're curios as to how it works internally, then feel free to checkout the source code of some of the plugins that offer this functionality. A very simple explanation can be found at this link - http://www.openjs.com/articles/ajax/ajax_file_upload/

但是,如果您对它的内部工作方式感到好奇,那么请随时查看一些提供此功能的插件的源代码。可以在此链接中找到一个非常简单的解释 - http://www.openjs.com/articles/ajax/ajax_file_upload/

Basically, you change the form targetto submit inside an <iframe>, thus avoiding the page refresh, and simulating AJAX, which it isn't really, but who cares - the end user can't tell.

基本上,您将表单更改target为在 内提交<iframe>,从而避免页面刷新,并模拟 AJAX,这不是真的,但谁在乎 - 最终用户无法分辨。

A minimal example for an iframe based upload may look like this:

基于 iframe 的上传的最小示例可能如下所示:

?$("#upComplete").click(function() {
    // create a dynamic iframe, or use existing one 
    var iframe = $("<iframe id='f' name='f' src=''>");
    // attach a load event to handle response/ know about completion
    iframe.load(function() { alert('complete'); });
    iframe.appendTo('body');
    // change form's target to the iframe (this is what simulates ajax)
    $('#uploadForm').attr('target', 'f');
    $('#uploadForm').submit();
});??????

Note that this does not do any response handling, but just sends the picture to the server. To handle the response, a callback must be written for the iframe's loadevent.

请注意,这不会进行任何响应处理,而只是将图片发送到服务器。要处理响应,必须为 iframe 的load事件编写回调。

回答by albanx

Actually there is a method to upload files with ajax (xmlhttp) with Firefox>3 and Chrome, it's also possible to upload multiple files without using forms and iframes. Actually I am making a jQuery plugin for doing this and soon I will publish it. Here is a simple example:

实际上有一种方法可以使用 Firefox>3 和 Chrome 使用 ajax (xmlhttp) 上传文件,也可以在不使用表单和 iframe 的情况下上传多个文件。实际上,我正在为此制作一个 jQuery 插件,很快我将发布它。这是一个简单的例子:

var file=$('<input type=file />').get(0).files[0];
function asyncupload(file)
{
    var xhr = new XMLHttpRequest();    
    xhr.onreadystatechange = function() 
    {  
        if (xhr.readyState == 4) 
        {  
            if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) 
            {  
                //alert(xhr.responseText);
            }  
        }  
    };  
    xhr.upload.onload=function(e)
    {
        $('div#axprogress').progressbar("option", "value", 100);;
    };  
    xhr.upload.onprogress=function(e) 
    {  
        if (e.lengthComputable) 
        {  
            var perc = Math.round((e.loaded * 100) / e.total);  
            $('div#axprogress').progressbar("option", "value", perc);
        }  
    };  

    xhr.open("POST", "upload.php?filename="+file.name,true);  
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader("X-File-Name", encodeURIComponent(file.name));
    xhr.send(file);  
    return xhr;
}

For getting files in server side, like php, have to do this for upload.php:

为了在服务器端获取文件,如 php,必须为 upload.php 执行此操作:

$input = fopen("php://input", "r");
$temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp);
fclose($input);

if ($realSize != $this->getSize())
    {            
    return false;
}

$target = fopen($_GET['filename'], "w");        
fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target);
fclose($target); 

This is an simple idea example not the complete working script. Hope this helps. For more info refer to https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

这是一个简单的想法示例,而不是完整的工作脚本。希望这可以帮助。有关更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

回答by bobince

Whilst you could create a multipart/form-datarequest body yourself to include a file upload field, it's not going to help you because you cannot read client-side files from the file upload field.

虽然您可以multipart/form-data自己创建请求正文以包含文件上传字段,但它不会帮助您,因为您无法从文件上传字段读取客户端文件。

(Except using the FileListinterface, but currently only Firefox supports that.)

(除了使用FileList接口,但目前只有 Firefox 支持。)

回答by user3789888

   <input type="file" id="picfile" name="picf" />
       <input type="text" id="txtName" style="width: 144px;" />
  <input type="button" value=" ADD " id="btncatsave" style="width: 75px" />
 $("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;

                    var file = document.getElementById("picfile").files[0];
                    formData.append("FileUpload", file);
                    formData.append("Name", Name);

$.ajax({
                    type: "POST",
                    url: '/Category_Subcategory/Save_Category',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (msg) {

                                 alert(msg);

                    },
                    error: function (error) {
                        alert("errror");
                    }
                });

});

 [HttpPost]
    public ActionResult Save_Category()
    {
      string Name=Request.Form[1]; 
      if (Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
         }


    }