最近公司有个项目要做,时间比较紧,公司同事推荐一款JQgrid,打开官网一看效果不错,所以公司花了$449买了个,使用起来感觉不错,开发简单模块速度快~超赞,基本的实例代码可以看官方Demo:http://www.trirand.net/demoaspnet.aspx

     最近使用中发现一个问题,该控件不支持上传,最近刚接触JQuery,所以就找了个JQuery插件完成上传功能。具体实现如下:

控件AjaxFileUpload,控件地址http://www.phpletter.com/Our-Projects/AjaxFileUpload/

在JqGrid列中设置 EditType="Custom" EditTypeCustomCreateElement="ImgUpload" EditTypeCustomGetValue="GetImgValue"

前台JS代码

1 <script type="text/javascript">
2  //生成控件,用个hidden来隐藏得到的上传地址,也可以直接获取Img的Src
3 function ImgUpload(value, editOptions) {
4 var span = $("<span>");
5 var hiddenValue = $("<input>", { type: "hidden", val: value, name: "fileName", id: "fileName" });
6 var image = $("<img>", { name: "uploadimage", id: "uploadimage",style:"display:none; width:150px; height:80px" });
7 var el = document.createElement("input");
8 el.type = "file"
9 el.id = "imgFile";
10 el.name = "imgFile";
11 el.onchange = UploadFile;
12 span.append(el).append(hiddenValue ).append(image);
13 return span;
14 }
15
16 function UploadFile(){
17 $.ajaxFileUpload
18 ({
19 url: 'UploadFile.aspx',
20 secureuri: false,
21 fileElementId: 'imgFile',
22 dataType: 'json',
23 success: function(data, status) {
24 if (typeof (data.error) != 'undefined') {
25 if (data.error != '') {
26 alert(data.error);
27 } else {
28 $("#fileName").val(data.msg);
29 $("#uploadimage").attr("src", "../Upload/Web/" + data.msg);
30 $("#uploadimage").show();
31 $("#imgFile").hide();
32 }
33 }
34 },
35 error: function(data, status, e) {
36 alert(e);
37 }
38 })
39
40 return false;
41 }
42 function GetImgValue(elem, sg, value) {
43 return $(elem).find("#fileName").val();
44 }
45 </script>

UploadFile.aspx后台代码

1 protected void Page_Load(object sender, EventArgs e)
2 {
3 HttpFileCollection files = Request.Files;
4 string msg = string.Empty;
5 string error = string.Empty;
6 if (files.Count > 0)
7 {
8 string fileName = new WebInfoManger().GetFileName(files[0].FileName, "WEB");
9 string path = Server.MapPath("../UpLoad//Web//" + DateTime.Now.Year + "//" + DateTime.Now.Month);
10 string type = Path.GetExtension(fileName);
11 if (ValidateType(type))
12 {
13 path = path + "//" + "Image";
14 if (!Directory.Exists(path))
15 Directory.CreateDirectory(path);
16 files[0].SaveAs(path + "//" + fileName);
17 msg = DateTime.Now.Year + "/" + DateTime.Now.Month + "/Image/" + fileName;
18 }
19 else
20 {
21 error = "类型错误";
22 }
23 string res = "{ error:'" + error + "', msg:'" + msg + "'}";
24 Response.Write(res);
25 Response.End();
26 }
27
28
29 }

即可完成图片上传,

潍坊程序员之家 欢迎潍坊地区软件开发人员 地址:http://www.noicn.com

posted on 2011-03-22 15:33  桔子人  阅读(7009)  评论(4编辑  收藏  举报