jQuery表单图片上传

时间:2013-01-29 08:49:47

标签: jquery jquery-plugins

我最近尝试使用http://malsup.com/jquery/form/#file-upload进行文件上传,但我不完全确定如何将图像上传到服务器上的某个文件夹。

继承人jQuery:

(function() {

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

$('form').ajaxForm({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
        //console.log(percentVal, position, total);
    },
    complete: function(xhr) {
        status.html(xhr.responseText);
    }
}); 

})();

然后是HTML:

<h1>File Upload Progress Demo #3</h1>
<code>&lt;input type="file" name="myfile[]"></code><br>
<code>&lt;input type="file" name="myfile[]"></code><br>
<code>&lt;input type="file" name="myfile[]"></code>
<form action="files-raw.php" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile[]"><br>
    <input type="file" name="myfile[]"><br>
    <input type="file" name="myfile[]"><br>
    <input type="submit" value="Upload File to Server">
</form>

<div class="progress">
    <div class="bar"></div >
    <div class="percent">0%</div >
</div>

<div id="status"></div>

2 个答案:

答案 0 :(得分:1)

服务器端代码负责将上传的文件保存到服务器。当您使用PHP时,您可以通过$_FILES["myfile"]访问该文件。我假设你想要这样的代码,

$newdirectory = "/your/directory";
$count = 0;
foreach ($_FILES['myfile']['name'] as $filename)
{
    $temp = $_FILES['myfile']['tmp_name'][$count];
    move_uploaded_file($temp, $newdirectory . '/' . basename($filename));
    $count++;
}

这应该按照你的要求去做。有关处理上传heremove_uploaded_file here

的更多信息

答案 1 :(得分:0)

如果它在MVC中则在视图中

<form action="Home/HandleFileUpload" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile[]"><br>
    <input type="file" name="myfile[]"><br>
    <input type="file" name="myfile[]"><br>
    <input type="submit" value="Upload File to Server">
</form>

并在Controller中写这个......

[HttpPost]
        public ActionResult HandleFileUpload()
        {
            if (!string.IsNullOrEmpty(Request.Headers["X-File-Name"]))
            {
                string path = Server.MapPath(string.Format("~/Uploads/{0}", Request.Headers["X-File-Name"]));
                using (var fileStream = new FileStream(path, FileMode.OpenOrCreate))
                {
                    Request.InputStream.CopyTo(fileStream);
                }

                return this.Json(new { success = true });
            }

            return this.Json(new { success = false });
        }
       }