• Aspx.net 上传图片并显示预览实现个人简历


    使用js插件和imput file实现上传图片,并显示预览图片功能。经常用在用户个人信息页面,用户选择个人证件照片—预览—上传—保存数据库。Codeby lanhai96

    实现效果如下图:

     页面右侧,用户点击“选择文件”,显示下图

     选择自己的用户照片,在右侧的图片窗口就会显示用户选择图片的预览。

     用户确定无误后,点击上传,此时图片根据规则已上传至服务器指定地址。

    最后,用户修改其他信息,如姓名,修改完毕后:

     点击保存,将实现修改的信息和修改的图片一起保存到数据库。

     保存数据成功后,将刷新显示当前修改的信息。

     以上功能使用bootstrap框架,支持除IE 8以下外的所有主流浏览器。

    实现以上功能的核心代码如下:

    1、引入关键的js和css文件

      <script type="text/javascript" src="./Scripts/jquery-1.8.1.min.js">script>

            <script type="text/javascript" src="./Scripts/CJL.0.1.min.js">script>

            <script type="text/javascript" src="./Scripts/QuickUpload.js">script> 

            <script type="text/javascript" src="./Scripts/jquery.form.js">script>

    其他样式文件略

    2、body中的关键元素

    1. <tr>
    2.                                                             <td>
    3.                                                                 姓名:
    4.                                                             td>
    5.                                                             <td>
    6.                                                                 <asp:HiddenField ID="hid_userid" runat="server" Value="" />
    7.                                                                 <input id="username" type="text" class="form-control" value='<%=username %>'  />
    8.                                                             td>
    9.                                                             <td>
    10.                                                                 电话:
    11.                                                             td>
    12.                                                             <td>
    13.                                                                 <input id="telphone" type="text" class="form-control" value='<%=telphone %>' />
    14.                                                             td>
    15.                                                             <td>
    16.                                                                 拼音:
    17.                                                             td>
    18.                                                             <td>
    19.                                                                 <input type="text" class="form-control" value='<%=pinyin %>' />
    20.                                                             td>
    21.                                                             <td rowspan="3" style="padding-left:15px;height:180px;width:150px;">
    22.                                                               
    23.                                                                 <div id="hidpic" style="  visibility:hidden;" runat="server"><%=photo %>div>                                                               
    24.                                                                
    25.                                                                 <div>               
    26.                                                                     <img id="idImg"    style="width:195px;height:240px;" title="照片"/>
    27.                                                                 div>
    28.                                                                 <div style="margin:10px;float:left;">
    29.                                                                     <span id="filebtn" class="btn" >选择文件:span>
    30.                                                                     <div  style="height:20px;width:50px;border-radius:4px;background-color:green;visibility:hidden;">
    31.                                                                         <input id="idFile" runat="server" name="pic" type="file"   />
    32.                                                                     div>
    33.                                                                 div>
    34.                                                                 <div style="margin-top: 10px;">
    35.                                                                    
    36.                                                                     <input type="button" name="resets" value="上传" class="btn" onclick="upLoadFile()" />
    37.                                                                 div>
    38.                                                             td>
    39.                                                         tr>

    3、前台关键的函数和方法

     图片通过ajax方法上传,上传后通过js插件来显示预览

    1. function clearFileInput() {
    2. var form = document.createElement('form1');
    3. document.body.appendChild(form);
    4. //记住file在旧表单中的的位置
    5. var file = document.getElementById("idFile");
    6. var pos = file.nextSibling;
    7. form.appendChild(file);
    8. form.reset();//ͨ重置form下的窗口
    9. document.getElementById("colspan").appendChild(file);
    10. document.body.removeChild(form);
    11. //获取图片元素对象
    12. document.getElementById("idImg").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='images/noimage.jpg'";
    13. $("#idImg").attr('src', 'images/noimage.jpg');
    14. $("#idImg").removeAttr('src');
    15. $("#idImg").removeAttr('style');
    16. }
    17. function upLoadFile() {
    18. $('#form1').ajaxSubmit({
    19. semantic: true,
    20. type: 'post',
    21. url: './userphotofile.ashx',//调用后台程序上传图片到指定位置
    22. success: function (result) {
    23. if (result == "false") {
    24. alert("失败");
    25. }
    26. else {
    27. $('#hidpic').html(result);//上传成功后,记录图片路径
    28. alert("成功");
    29. }
    30. },
    31. error: function (result) {
    32. alert("失败" + result);
    33. }
    34. });
    35. }
    36. $(document).ready(function () {
    37. $('#filebtn').click(function () {
    38. $('#idFile').click();
    39. });
    40. });

    以下的图片预览的js要放到页面的最后:

    1. <script type="text/javascript" src="./Scripts/ImagePreview.js">script>
    2. <script type="text/javascript">
    3. var ip = new ImagePreview($$("idFile"), $$("idImg"), {
    4. maxWidth: 200, maxHeight: 200, action: "./ImagePreview.ashx"
    5. });
    6. ip.img.src = ImagePreview.TRANSPARENT;
    7. ip.file.onchange = function () { ip.preview(); };
    8. script>

    文件修改完成后,同样使用ajax方式,实现所有数据的最终保存。

    1. $('#save').click(function () {
    2. var name = $('#username').val();
    3. var userid = $('#hid_userid').val();
    4. var telphone = $('#telphone').val();
    5. var hidpicpath = $('#hidpic').html();
    6. var userjson;
    7. userjson = {
    8. UserID: userid,
    9. UserName: name,
    10. Usertelephone: telphone,
    11. UserPhoto: hidpicpath
    12. };
    13. var tr_data = JSON.stringify(userjson);
    14. $.ajax({
    15. contentType: "application/json",
    16. type: "post",
    17. datatype: "json",
    18. url: "index.aspx/Save",
    19. data: "{'data':'" + tr_data + "'}",
    20. success: function (msg) {
    21. alert("保存成功");
    22. window.location.href = "index.aspx";
    23. },
    24. error: function (x) {
    25. alert("失败" + x);
    26. window.location.href = "index.aspx";
    27. }
    28. });
    29. });

    4、后台代码部分

    1. //页面加载时,初始化的数据
    2. protected void InitData(string userid)
    3. {
    4. Users user = new Users();
    5. DataTable dt = DBHelp.GetDataSet("select * from Users");
    6. username = dt.Rows[0]["UserName"].ToString() ;
    7. pinyin = dt.Rows[0]["UserPinYin"].ToString();
    8. if (dt.Rows[0]["UserPhoto"].ToString() != null || dt.Rows[0]["UserPhoto"].ToString() != "./image/noimage.jpg" || dt.Rows[0]["UserPhoto"].ToString() != "")
    9. {
    10. photo = dt.Rows[0]["UserPhoto"].ToString();
    11. }
    12. else
    13. user.UserPhoto = "./image/noimage.jpg";
    14. if (dt.Rows[0]["telephone"].ToString() != null || dt.Rows[0]["telephone"].ToString() != "")
    15. {
    16. telphone = dt.Rows[0]["telephone"].ToString();
    17. }
    18. else
    19. {
    20. telphone = "";
    21. }
    22. }
    1. //ajax调用后台时的方法
    2. [WebMethod]
    3. public static bool Save(string data)
    4. {
    5. JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
    6. Users _jsondutydata = jsonSerializer.Deserialize(data);
    7. Users user = new Users();
    8. user.UserID = _jsondutydata.UserID;
    9. user.UserName = _jsondutydata.UserName;
    10. user.Usertelephone = _jsondutydata.Usertelephone;
    11. user.UserPhoto = _jsondutydata.UserPhoto;
    12. string sql = "Update Users Set UserName=@Username,UserPhoto=@UserPhoto,telephone=@userphone where UserID='" + user.UserID + "'";
    13. SqlParameter[] para = new SqlParameter[]
    14. {
    15. new SqlParameter("@Username",user.UserName),
    16. new SqlParameter("@UserPhoto",user.UserPhoto),
    17. new SqlParameter("@userphone",user.Usertelephone)
    18. };
    19. int i = DBHelp.ExecuteCommand(sql, para);
    20. if (i > 0)
    21. {
    22. return true;
    23. }
    24. else
    25. {
    26. return false;
    27. }
    28. }

    5、两个处理程序的代码

    Userphotofile.ashx

    //用户图片上传

    1. public class userphotofile : IHttpHandler
    2. {
    3. public void ProcessRequest(HttpContext context)
    4. {
    5. // context.Response.ContentType = "text/plain";
    6. string res = "";
    7. HttpFileCollection files = context.Request.Files;
    8. if (files.Count > 0)
    9. {
    10. Random rnd = new Random();
    11. for (int i = 0; i < files.Count; i++)
    12. {
    13. HttpPostedFile file = files[i];
    14. if (file.ContentLength > 0)
    15. {
    16. string fileName = file.FileName;
    17. string extension = Path.GetExtension(fileName);
    18. int num = rnd.Next(5000, 10000);
    19. string path = "./photo/" + num.ToString() + extension;
    20. file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));
    21. res = path.Substring(1, path.Length - 1);
    22. //更新该用户数据库
    23. }
    24. }
    25. context.Response.Write(res);
    26. }
    27. else
    28. {
    29. context.Response.Write("false");
    30. }
    31. }

    ImagePreview.ashx

    //图片预览处理程序

    1. public void ProcessRequest(HttpContext context)
    2. {
    3. if (context.Request.Files.Count > 0)
    4. {
    5. HttpPostedFile file = context.Request.Files[0];
    6. if (file.ContentLength > 0 && file.ContentType.IndexOf("image/") >= 0)
    7. {
    8. int width = Convert.ToInt32(context.Request.Form["width"]);
    9. int height = Convert.ToInt32(context.Request.Form["height"]);
    10. string path = "data:image/jpeg;base64," + Convert.ToBase64String(ResizeImg(file.InputStream, width, height).GetBuffer());
    11. context.Response.Write(path);
    12. }
    13. }
    14. }
    15. public MemoryStream ResizeImg(Stream ImgFile, int maxWidth, int maxHeight)
    16. {
    17. Image imgPhoto = Image.FromStream(ImgFile);
    18. decimal desiredRatio = Math.Min((decimal)maxWidth / imgPhoto.Width, (decimal)maxHeight / imgPhoto.Height);
    19. int iWidth = (int)(imgPhoto.Width * desiredRatio);
    20. int iHeight = (int)(imgPhoto.Height * desiredRatio);
    21. Bitmap bmPhoto = new Bitmap(iWidth, iHeight);
    22. Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
    23. gbmPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(0, 0, imgPhoto.Width, imgPhoto.Height), GraphicsUnit.Pixel);
    24. MemoryStream ms = new MemoryStream();
    25. bmPhoto.Save(ms, ImageFormat.Jpeg);
    26. imgPhoto.Dispose();
    27. gbmPhoto.Dispose();
    28. bmPhoto.Dispose();
    29. return ms;
    30. }

    数据库操作的代码这里省略了,详细功能可以参考源码。源码和数据库下载地址https://download.csdn.net/download/lanhai96/86398822

    几个注意事项:

    1、js中调用的form1,是form的id;

    2、form中要配置enctype参数,不然不能传递对象。

    <form id="form1" runat="server" method="post" enctype="multipart/form-data">

    3、使用ajaxSubmit要引用jquery.form.js,同时配置semantic参数为true,才能支持极速360等主流浏览器,不然只支持firefox浏览器。

    $('#form1').ajaxSubmit({

                    semantic: true,

    4、注意留心JSON对象的创建和解析。

    5、[WebMethod]的用法:带有这个标识的方法,可以在在前端直接利用ajax方法调用

    6、文章全为原创,码字不易,转载请注明蓝海云梦。

  • 相关阅读:
    cesium加载高层级离线影像地图瓦片(天地图、19级Arcgis)
    60. UE5 RPG 使用场景查询系统(EQS,Environment Query System)实现远程敌人寻找攻击位置
    WebRTC系列-网络传输之7-ICE补充之偏好(preference)与优先级(priority)
    JavaScript实现在HTML中的粒子文字特效
    从理论到实践:如何用 TDengine 打造完美数据模型​
    深入探究MinimalApi是如何在Swagger中展示的
    微软 SQL 服务器被黑,带宽遭到破坏
    新库上线 | CnOpenData中国审计年鉴数据
    面试:HashMap
    浅层神经网络和深层神经网络介绍
  • 原文地址:https://blog.csdn.net/lanhai96/article/details/126295313