马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

web端上传图片到服务器

  [复制链接]
查看17056 | 回复10 | 2017-9-30 13:42:27 | 显示全部楼层 |阅读模式
前端:

[HTML] 纯文本查看 复制代码
<form runat="server" id="form1" method="post" enctype="multipart/form-data">   <label>物流快照:</label>
   <input type="file" id="upload" name="upload" accept="image/*" />
   <div id="photo"></div>
   <input type="hidden" value="" id="hideimg" />
</form>



引入两个js文件
jquery.min.js和jquery-form.js

[JavaScript] 纯文本查看 复制代码
$('#upload').change(function () {
            var file = this.files[0];
            var r = new FileReader();
            r.readAsDataURL(file);
            $(r).load(function () {
                $("#form1").ajaxSubmit({
                    success: function (str) {
                        var data = JSON.parse(str);

                        if (data.msg != "") {
                            $('#photo').html('<img src="' + data.filenewname + '" alt="" />');
                            $("#hideimg").val(data.filenewname);
                        } else {
                            layer.open({ content: '上传失败!', skin: 'msg', time: 3 });
                        }
                    },
                    error: function (error) { alert(error); },
                    url: 'UploadImage.ashx', /*设置post提交到的页面*/
                    type: "post", /*设置表单以post方法提交*/
                    dataType: "text" /*设置返回值类型为文本*/
                });
            });
        });





后台代码,用的一般处理程序
[C#] 纯文本查看 复制代码
string msg = string.Empty;
            string error = string.Empty;
            string result = string.Empty;
            string filePath = string.Empty;
            string fileNewName = string.Empty;
            string filename=string.Empty;
            //这里只能用<input type="file" />才能有效果,因为服务器控件是HttpInputFile类型
            HttpFileCollection files = context.Request.Files;
            if (files.Count > 0)
            {
                BLL.bll_Setting setting = new BLL.bll_Setting();
                DataTable dt = setting.SelectSetting("8");
                string uri = dt.Rows[0]["FValue"].ToString();
                string thechar=uri.Substring(uri.Length-1,1);
                if (thechar=="/")
                {
                    uri = uri.Remove(uri.Length - 1, 1);
                }
                fileNewName = DateTime.Now.ToString("yyyyMMddHHmmssfff") +"."+ System.IO.Path.GetFileName(files[0].FileName).Split('.')[1];
                filename=fileNewName.Substring(0,8);
                //保存文件
                string dir = context.Server.MapPath("~/upload/"+filename);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                files[0].SaveAs(context.Server.MapPath("~/upload/"+filename+"/" + fileNewName));
                string relativeFileFullPath = context.Server.MapPath("~/upload/" + filename + "/" + fileNewName);
                string data = UploadFile.Upload_Request(uri + "/SaveForm.aspx?action=seorder", relativeFileFullPath, fileNewName);
                string imgurl = uri + "/SEOrderImages/" + filename + "/" + fileNewName;
                msg = "文件上传成功!";
                result = "{\"msg\":\"" + msg + "\",\"filenewname\":\"" + imgurl + "\"}";
            }
            else
            {
                error = "文件上传失败!";
                result = "{\"error\":\"" + error + "\"}";
            }
            context.Response.Write(result);
            context.Response.End();


UploadFile.cs
[C#] 纯文本查看 复制代码
/// <summary> 
        /// 将本地文件上传到指定的服务器(HttpWebRequest方法) 
        /// </summary> 
        /// <param name="address">文件上传到的服务器</param> 
        /// <param name="fileNamePath">要上传的本地文件(全路径)</param> 
        /// <param name="saveName">文件上传后的名称</param> 
        /// <returns>成功返回Success,失败返回Error</returns> 
        public static string Upload_Request(string address, string fileNamePath, string saveName)
        {
            string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");     //请求头部信息
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            httpReq.AllowWriteStreamBuffering = false;     //设置获得响应的超时时间(300秒) 
            httpReq.Timeout = 300000;
            httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;

            string returnValue = "";
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
            BinaryReader r = new BinaryReader(fs);     //时间戳 
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append("file");
            sb.Append("\"; filename=\"");
            sb.Append(saveName);
            sb.Append("\";");
            sb.Append("\r\n");
            sb.Append("Content-Type: ");
            sb.Append("application/octet-stream");
            sb.Append("\r\n");
            sb.Append("\r\n");
            string strPostHeader = sb.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);     // 根据uri创建HttpWebRequest对象 

            long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
            long fileLength = fs.Length;
            httpReq.ContentLength = length;
            try
            {
                int bufferLength = 1024;
                byte[] buffer = new byte[bufferLength]; //已上传的字节数 
                long offset = 0;         //开始上传时间 
                DateTime startTime = DateTime.Now;
                int size = r.Read(buffer, 0, bufferLength);
                Stream postStream = httpReq.GetRequestStream();         //发送请求头部消息 
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

                //progressBar.Position = 0;

                while (size > 0)
                {
                    postStream.Write(buffer, 0, size);
                    offset += size;
                    //Application.DoEvents();
                    size = r.Read(buffer, 0, bufferLength);
                }
                //添加尾部的时间戳 
                postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                postStream.Close();         //获取服务器端的响应 
                WebResponse webRespon = httpReq.GetResponse();
                Stream s = webRespon.GetResponseStream();
                //读取服务器端返回的消息
                StreamReader sr = new StreamReader(s);
                String sReturnString = sr.ReadLine();
                s.Close();
                sr.Close();
                returnValue = sReturnString;
            }
            catch (Exception ex)
            {
                returnValue = ex.ToString();
            }
            finally
            {
                fs.Close();
                r.Close();
            }
            return returnValue;




服务器
[C#] 纯文本查看 复制代码
string action = Request.QueryString["action"];

            if (Request.Files.Count > 0)
            {
                try
                {
                    //获取根目录路径

                    string M_Path = Server.MapPath("~/");
                    HttpPostedFile file = Request.Files[0];
                    string time = file.FileName.Substring(0, 8);
                    string filePath = "";
                    if (action == "icitem")
                    {
                        if (Directory.Exists(M_Path+"ICItemImages/" + time) == false)//如果不存在就创建file文件夹

                        {
                            Directory.CreateDirectory(M_Path + "ICItemImages/" + time);
                        }
                        filePath = M_Path + "ICItemImages/" + time + "/" + file.FileName;
                    }
                    if (action == "seorder")
                    {
                        if (Directory.Exists(M_Path + "SEOrderImages/" + time) == false)//如果不存在就创建file文件夹

                        {
                            Directory.CreateDirectory(M_Path + "SEOrderImages/" + time);
                        }
                        filePath = M_Path + "SEOrderImages/" + time + "/" + file.FileName;
                    }
                    file.SaveAs(filePath);
                    Response.Write("Success");
                }
                catch (Exception ex)
                {
                    Response.Write(ex);
                }
            }
            else
            {
                Response.Write("Error");
            }















洛水千尘 | 2017-9-30 13:43:04 | 显示全部楼层
1111
ibcadmin | 2017-9-30 14:42:48 | 显示全部楼层
222
C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
ibcadmin | 2017-9-30 14:50:25 | 显示全部楼层
代码记得用那个格式化的显示,~  我先编辑了,  奖励1元

点评

略略略,晓得了  详情 回复 发表于 2017-9-30 16:06
C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
桂林一枝花 | 2017-9-30 15:00:06 | 显示全部楼层
这都能奖励1块,,我也上传几年前的C#代码

点评

过时了  详情 回复 发表于 2017-9-30 16:07
huok | 2017-9-30 15:48:32 | 显示全部楼层
顶!d=====( ̄▽ ̄*)b

点评

^ω^  详情 回复 发表于 2017-9-30 16:08
洛水千尘 | 2017-9-30 16:06:14 来自手机 | 显示全部楼层
ibcadmin 发表于 2017-9-30 14:50
代码记得用那个格式化的显示,~  我先编辑了,  奖励1元

略略略,晓得了
洛水千尘 | 2017-9-30 16:07:35 来自手机 | 显示全部楼层
桂林一枝花 发表于 2017-9-30 15:00
这都能奖励1块,,我也上传几年前的C#代码

过时了
洛水千尘 | 2017-9-30 16:08:22 来自手机 | 显示全部楼层
huok 发表于 2017-9-30 15:48
顶!d=====( ̄▽ ̄*)b

^ω^
min | 2017-11-7 08:44:32 | 显示全部楼层
先评论 后学习
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则