js 上传文件

前端代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RecUpload.aspx.cs" Inherits="ActivityFile_RecUpload" %>

<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>文件上传</title>
</head>
<body>
    <form id="form1" runat="server" action="#" method="post" enctype="multipart/form-data">
        <div style="margin-left: 20px; margin-top: 50px;">
            选择照片:<input type="file" id="File" name="Task" style="margin-left: 5px; height: 25px;" />
            <input type="button" value="上传" style="margin-left: 30px; height: 25px;" onclick="Upload()" />
        </div>

    </form>
    <script type="text/javascript" src="../JavaScript/UserControl/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">

        function Upload() {
            var file = document.getElementById('File').files[0];
            if (file != null) {
                var fd = new FormData();
                fd.append("File", file);
                //需把本地Internet级别设置为低才可访问
                xhrupload(fd, "Url");//接口地址
                return false;//阻止表单提交
            }
            else {
                alert("请选择需要上传的文件");
                return false;
            }
        }
        function xhrupload(fd, url) {
            var xhr = new XMLHttpRequest();
            xhr.open("post", url, true);
            xhr.onreadystatechange = function () {

                if (xhr.readyState == 4) {
                    if (200 == xhr.status) {
                        alert("上传成功");
                        document.getElementById('File').value = "";
                        //window.close();
                    }
                    else alert(xhr.responseText);
                }
            }
            xhr.send(fd);
        }
    </script>
</body>
</html>

后台

 string date = DateTime.Now.ToString("yyyyMMdd");
 string filepath = HttpContext.Current.Server.MapPath("~/Files/Uploads/" + date + "");//项目路径
 string Name = Guid.NewGuid().ToString() + Type;
 if (!Directory.Exists(filepath))//判断路径是否存在
 {
     Directory.CreateDirectory(filepath);//创建路径
 }   
 HttpContext.Current.Request.Files[0].SaveAs(filepath + "\\" + Name);//保存
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值