html5 file上传图片

1)html+js代码如下

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript">
        //选择图片,c#默认请求大小4M。
        //如果需求需要大于4M,修改httpRuntime下的maxRequestLength
        //单位为:K 
        function fileSelected() {
            var files = document.getElementById('fileToUpload').files;
            if (files.length > 0) {
                var fileInfo = '';
                for (var i = 0; i < files.length; i++) {
                    fileInfo += 'Name: ' + files[i].name + '<br/>';
                    fileInfo += 'Size: ' + files[i].size + '<br/>';
                    fileInfo += 'Type: ' + files[i].type + '<br/>';
                }
                document.getElementById('fileInfo').innerHTML = fileInfo;
            }
        }
        function uploadFile() {//上传图片
            var files = document.getElementById('fileToUpload').files;
            if (files.length > 0) {
                var fd = new FormData();
                for (var i = 0; i < files.length; i++) {
                    fd.append("fileToUpload", files[i]);
                }
                var xhr = new XMLHttpRequest();
                xhr.upload.addEventListener("progress", uploadProgress, false);
                xhr.addEventListener("load", uploadComplete, false);
                xhr.addEventListener("error", uploadFailed, false);
                xhr.addEventListener("abort", uploadCanceled, false);
                xhr.open("POST", "Home/Upload");
                xhr.send(fd);
            } else {
                alert('请选择上传的图片!');
            }
        }
        function uploadProgress(evt) {//上传中
            if (evt.lengthComputable) {
                var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
            }
            else {
                document.getElementById('progressNumber').innerHTML = 'unable to compute';
            }
        }
        function uploadComplete(evt) {//上传完成
            /* This event is raised when the server send back a response */
            alert(evt.target.responseText);
        }

        function uploadFailed(evt) {//上传失败
            alert("There was an error attempting to upload the file.");
        }
        function uploadCanceled(evt) {//上传被取消
            alert("The upload has been canceled by the user or the browser dropped the connection.");
        }
    </script>
</head>
<body>
    <div>
        <input type="file" name="fileToUpload" id="fileToUpload" multiple="multiple" οnchange="fileSelected();" />
        <input type="button" οnclick="uploadFile()" value="Upload Image" />
        <div id="fileInfo"></div>
        <div id="progressNumber"></div>
    </div>
</body>
</html>
2)Web API代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication26.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="fileToUpload"></param>
        /// <returns>图片上传成功返回true,上传失败返回false,如果没有图片上传返回true</returns>
        [HttpPost]
        public bool Upload(HttpPostedFileBase[] fileToUpload)
        {
            try
            {
                string dir = Server.MapPath("~/UploadImages");
                if (!Directory.Exists(dir))//文件夹不存在  
                {
                    Directory.CreateDirectory(dir);//创建文件夹  
                } 
                if (fileToUpload != null && fileToUpload.Length > 0)
                {
                    foreach (HttpPostedFileBase file in fileToUpload)
                    {
                        string path = System.IO.Path.Combine(dir, System.IO.Path.GetFileName(file.FileName));
                        file.SaveAs(path);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值