extjs上传图片预览
 <?
<?
require_once('../classfile/guid.class.php');
if(!isset($_FILES['imgFile'])){
	echojson_encode(array("success"=>false,'msg'=>"NotgetImgfile"));
	return;
}
$upfile=$_FILES['imgFile'];
$name=$upfile["name"];//上传文件的文件名
$type=$upfile["type"];//上传文件的类型
$size=$upfile["size"];//上传文件的大小
$tmp_name=$upfile["tmp_name"];//上传文件的临时存放路径
$error_cod=$upfile["error"];
if($error_cod>0){
	echojson_encode(array("success"=>false,'msg'=>$error_cod));
}
$ext_file_name="";
switch($type){
	case'image/pjpeg':
		$okType=true;
		$ext_file_name	=".jpg";	
		break;
	case'image/jpeg':
		$okType=true;
		$ext_file_name	=".jpg";	
		break;
	case'image/gif':
		$okType=true;
		$ext_file_name	=".gif";	
		break;
	case'image/png':
		$okType=true;
		$ext_file_name	=".png";	
		break;
}
if(!$okType){
	echojson_encode(array("success"=>false,'msg'=>"Notimage"));
	return;
}
$web_root="D:".DIRECTORY_SEPARATOR."Easy2PHP5".DIRECTORY_SEPARATOR."webSiteJfz".DIRECTORY_SEPARATOR;
$photo_tmp_path=$web_root."img".DIRECTORY_SEPARATOR."userimg".DIRECTORY_SEPARATOR."temp";
$temp_file_name=creat_guid(0).$ext_file_name;
$photo_tmp_file_name=$photo_tmp_path.DIRECTORY_SEPARATOR.$temp_file_name;
$photo_tmp_file_scr="img".DIRECTORY_SEPARATOR."userimg".DIRECTORY_SEPARATOR."temp".DIRECTORY_SEPARATOR.$temp_file_name;
move_uploaded_file($tmp_name,$photo_tmp_file_name);
echojson_encode(array("success"=>true,'msg'=>"ok","file_name"=>$photo_tmp_file_name,"file_scr"=>$photo_tmp_file_scr));
//echojson_encode(array("success"=>false,'msg'=>json_encode($_FILES['imgFile'])));
return;
?>
guid.class.php//生成唯一的图片文件名
<?
functioncreat_guid($long){
	$uuid="";
if(function_exists('com_create_guid')){
$uuid=com_create_guid();
}else{
mt_srand((double)microtime()*10000);//optionalforphp4.2.0anp.
$charid=strtoupper(md5(uniqid(rand(),true)));
$hyphen=chr(45);//"-"
$uuid=chr(123)//"{"
				.substr($charid,0,8).$hyphen
.substr($charid,8,4).$hyphen
.substr($charid,12,4).$hyphen
.substr($charid,16,4).$hyphen
.substr($charid,20,12)
.chr(125);//"}"
//return$uuid;
}
	if(!isset($long)||$long==0){
		returnsubstr($uuid,1,strlen($uuid)-2);
	}else{
		return$uuid;
	}
}
❷ extjs 3.4中 怎么给htmlEdit添加图片插件 实现图片上传功能
首先要使用extjs自带的HTMLEditor,然后在原有的工具条上添加一个图片按钮,点击这个图片按钮要弹出窗口,这个窗口负责实现上传功能,实现上传后,要将上传的图片路径添加到HTMLEditor的光标处,并且要以<IMG></IMG>的方式,这样HTMLEditor才能解析出来。实现代码如下:
前台JSP页面
fieldLabel : '商品特性', 
id : 'shopSp.spTxms',
name : 'shopSp.spTxms', 
xtype : 'StarHtmleditor',
anchor : '93%'
这其中引用了StarHtmleditor,StarHtmleditor.js的代码如下,直接将代码复制下来,然后新建个JS,全复制进去就行了。
var HTMLEditor = Ext.extend(Ext.form.HtmlEditor, {
  addImage : function() {
    var editor = this;
    var imgform = new Ext.FormPanel({
      region : 'center',
      labelWidth : 55,
      frame : true,
      bodyStyle : 'padding:5px 5px 0',
      autoScroll : true,
      border : false,
      fileUpload : true,
      items : [{
            xtype : 'textfield',
            fieldLabel : '选择文件',
            id : 'UserFile',
            name : 'UserFile',
            inputType : 'file',
            allowBlank : false,
            blankText : '文件不能为空',
            anchor : '90%'
          }],
      buttons : [{
        text : '上传',
        handler : function() {
          if (!imgform.form.isValid()) {return;}
          imgform.form.submit({
            waitMsg : '正在上传......',
            url : 'HTMLEditorAddImgCommonAction.action',
            success : function(form, action) {
              var element = document.createElement("img");
							element.src = action.result.fileURL;
              if (Ext.isIE) {
                editor.insertAtCursor(element.outerHTML);
              } else {
                var selection = editor.win.getSelection();
                if (!selection.isCollapsed) {
                  selection.deleteFromDocument();
                }
                selection.getRangeAt(0).insertNode(element);
              }
              //win.hide();//原始方法,但只能传一个图片
              //更新后的方法
              form.reset();
    					win.close();
            },
            failure : function(form, action) {
              form.reset();
              if (action.failureType == Ext.form.Action.SERVER_INVALID)
                Ext.MessageBox.alert('警告','上传失败',action.result.errors.msg);
            }
          });
        }
      }, {
        text : '关闭',
        handler : function() {
          win.close(this);
        }
      }]
    })
    var win = new Ext.Window({
          title : "上传图片",
          width : 300,
          height : 200,
          modal : true,
          border : false,
          iconCls : "picture.png",
          layout : "fit",
          items : imgform
        });
    win.show();
  },
  createToolbar : function(editor) {
    HTMLEditor.superclass.createToolbar.call(this, editor);
    this.tb.insertButton(16, {
          cls : "x-btn-icon",
          icon : "picture.png",
          handler : this.addImage,
          scope : this
        });
  }
});
Ext.reg('StarHtmleditor', HTMLEditor);
JS的第一句var HTMLEditor = Ext.extend(Ext.form.HtmlEditor, 网上是没有var的,不用var不知道为什么总是报错,另外JS一定要与JSP的编码方式一致,要不然报莫名其妙的错误,而且错误都没有显示。
后台java代码
	/****
	 * HTMLEditor增加上传图片功能:
	 * 1、上传图片后,需要将图片的位置及图片的名称返回给前台HTMLEditor
	 * 2、前台HTMLEditor根据返回的值将图片显示出来
	 * 3、进行统一保存
	 * @param 上传图片功能
	 * @return JSON结果
	 * @throws IOException
	 */
	public void HTMLEditorAddImg() throws IOException {
		if(!"".equals(UserFile) && UserFile != null && UserFile.length() > 0){
			File path = ImportImg(UserFile, "jpg");
			UserFilePath = "../" + path.toString().replaceAll("\\", "/").substring(path.toString().replaceAll("\\", "/").indexOf("FileImg"));	
		}
		this.getResponse().setContentType("text/html");
		this.getResponse().getWriter().write("{success:'true',fileURL:'" + UserFilePath + "'}");
	}
特别要注意的是路径问题,路径问题主要有2点需要注意:
1、前台页面引用StarHtmleditor.js的路径一定要正确;
2、Htmleditor上传的图片路径一定要改,因为上传之后图片路径变为http://localhost:8080/,在正常使用中图片不显示,要将该地址替换为服务器的IP地址;替换方法如下:
//获取本地IP地址,因为extjs的htmleditor上传的照片路径有问题,需要将路径替换为本机IP地址
InetAddress inet = InetAddress.getLocalHost();
shopSp.setSpTxms(shopSp.getSpTxms().replace("localhost", inet.getHostAddress().toString()));
这样基本就完成了这个HTMLEditor上传图片功能。
如图:

❸ extjs怎样做图片上传
1.代码如下:
复制代码
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4     <title></title>
5     <!--ExtJs框架开始-->
6     <script type="text/javascript" src="/Ext/adapter/ext/ext-base.js"></script>
7     <script type="text/javascript" src="/Ext/ext-all.js"></script>
8     <script src="/Ext/src/locale/ext-lang-zh_CN.js" type="text/javascript"></script>
9     <link rel="stylesheet" type="text/css" href="/Ext/resources/css/ext-all.css" />
10     <!--ExtJs框架结束-->
11     <script type="text/javascript">
12         Ext.onReady(function () {
13             //初始化标签中的Ext:Qtip属性。
14             Ext.QuickTips.init();
15             Ext.form.Field.prototype.msgTarget = 'side';
16             //创建div组件
17             var imagebox = new Ext.BoxComponent({
18                 autoEl: {
19                     style: 'width:150px;height:150px;margin:0px auto;border:1px solid #ccc; text-align:center;padding-top:20px;margin-bottom:10px',
20                     tag: 'div',
21                     id: 'imageshow',
22                     html: '暂无图片'
23                 }
24             });
25             //创建文本上传域
26             var file = new Ext.form.TextField({
27                 name: 'imgFile',
28                 fieldLabel: '文件上传',
29                 inputType: 'file',
30                 allowBlank: false,
31                 blankText: '请浏览图片'
32             });
33             //提交按钮处理方法
34             var btnsubmitclick = function () {
35                 if (form.getForm().isValid()) {
36                     form.getForm().submit({
37                         waitTitle: "请稍候",
38                         waitMsg: '正在上传...',
39                         success: function (form, action) {
40                             Ext.MessageBox.alert("提示", "上传成功!");
41                             document.getElementById('imageshow').innerHTML = '<img style="width:150px;height:150px" src="' + action.result.path + '"/>';
42                         },
43                         failure: function () {
44                             Ext.MessageBox.alert("提示", "上传失败!");
45                         }
46                     });
47                 }
48             }
49             //重置按钮"点击时"处理方法
50             var btnresetclick = function () {
51                 form.getForm().reset();
52             }
53             //表单
54             var form = new Ext.form.FormPanel({
55                 frame: true,
56                 fileUpload: true,
57                 url: '/App_Ashx/Demo/Upload.ashx',
58                 title: '表单标题',
59                 style: 'margin:10px',
60                 items: [imagebox, file],
61                 buttons: [{
62                     text: '保存',
63                     handler: btnsubmitclick
64                 }, {
65                     text: '重置',
66                     handler: btnresetclick
67                 }]
68             });
69             //窗体
70             var win = new Ext.Window({
71                 title: '窗口',
72                 width: 476,
73                 height: 374,
74                 resizable: true,
75                 modal: true,
76                 closable: true,
77                 maximizable: true,
78                 minimizable: true,
79                 buttonAlign: 'center',
80                 items: form
81             });
82             win.show();
83         });
84     </script>
85 </head>
86 <body>
87 <!--
88 说明:
89 (1)var imagebox = new Ext.BoxComponent():创建一个新的html标记。
90     官方解释如下:
91     This may then be added to a Container as a child item.
92     To create a BoxComponent based around a HTML element to be created at render time, use the autoEl config option which takes the form of a DomHelper specification:
93 (2) autoEl: {style: '',tag: 'div',id: 'imageshow', html: '暂无图片'}定义这个html标记的属性,如 标记为:div,id是多少等。
94     官方实例为:
95     var myImage = new Ext.BoxComponent({
96     autoEl: {
97         tag: 'img',
98         src: '/images/my-image.jpg'
99         }
100     });
101 (3)var file = new Ext.form.TextField():创建一个新的文件上传域。
102 (4)name: 'imgFile':名称,重要,因为service端要根据这个名称接收图片。
103 (5)inputType: 'file':表单类型为文件类型。
104 (6)waitTitle: "请稍候",waitMsg: '正在上传...',:上传等待过程中的提示信息。
105 (7)document.getElementById('imageshow').innerHTML = '<img style="width:150px;height:150px" src="' + action.result.path + '"/>';这个是原生态的js,把imageshow的值换成图片。
106 -->
107 </body>
108 </html>
复制代码
其中与service交互用上传图片的 一般处理程序文件,源码如下:
/App_Ashx/Demo/Upload.ashx
复制代码
1 using System;
2 using System.Web;
3 using System.IO;
4 using System.Globalization;
5
6 namespace HZYT.ExtJs.WebSite.App_Ashx.Demo
7 {
8     public class Upload : IHttpHandler
9     {
10         public void ProcessRequest(HttpContext context)
11         {
12             //虚拟目录,建议写在配置文件中
13             String strPath = "/Upload/Image/";
14             //文件本地目录
15             String dirPath = context.Server.MapPath(strPath);
16             //接收文件
17             HttpPostedFile imgFile = context.Request.Files["imgFile"];
18             //取出文件扩展名
19             String fileExt = Path.GetExtension(imgFile.FileName).ToLower();
20             //重新命名文件
21             String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
22             //文件上传路径
23             String filePath = dirPath + newFileName;
24             //保存文件
25             imgFile.SaveAs(filePath);
26             //客户端输出
27             context.Response.Write("{success:true,path:'" + strPath + newFileName + "'}");
28         }
29
30         public bool IsReusable
31         {
32             get
33             {
34                 return false;
35             }
36         }
37     }
38 }
复制代码
2.效果如下:
无废话extjs
3.说明:
(1)上传域不光可以上传图片,还要以上传其他文件。这里我们以图片为例。
(2)在实际开发中,我们还要对图片格式,大小等进行校验,这个示例测重于上传,没有加入任何校验。
❹ extjs ajax 可以上传文件吗
文件上传的Ajax,首先Ajax并不支持流的传输,只是在里面套了个iframe。
//ajax上传
Ext.get('btn').on('click',function(){
Ext.Ajax.request({
url:'Upload.php',
isUpload:true,
form:'upform',
success:function(){
Ext.Msg.alert('upfile','文件上传成功!');
}
});
});
<formid="upform">
请选择文件:<inputtype="file"name="imgFile"/>
<inputtype="button"id="btn"value="上传"/>
</form>
<?php
if(!isset($_FILES['imgFile'])){
echojson_encode(array("success"=>false,'msg'=>"NotgetImgfile"));
return;
}
$upfile=$_FILES['imgFile'];
$name=$upfile["name"];//上传文件的文件名
$type=$upfile["type"];//上传文件的类型
$size=$upfile["size"];//上传文件的大小
$tmp_name=$upfile["tmp_name"];//上传文件的临时存放路径
$error_cod=$upfile["error"];
if($error_cod>0){
echojson_encode(array("success"=>false,'msg'=>$error_cod));
}
$photo_tmp_file_name=//这里设置存放路径
move_uploaded_file($tmp_name,$photo_tmp_file_name);//存储文件
?>
❺ htmleditor 如何上传图片
最近用Extjs做项目,用到htmleditor控件,唯一的缺陷是不可以上传图片,为了以后方便,在基于htmleditor控件上写了一个支持上传图片的。
控件StarHtmleditor
/**
 * 重载EXTJS-HTML编辑器
 * 
 * @class HTMLEditor
 * @extends Ext.form.HtmlEditor
 * @author wuliangbo
 */
HTMLEditor = Ext.extend(Ext.form.HtmlEditor, {
  addImage : function() {
    var editor = this;
    var imgform = new Ext.FormPanel({
      region : 'center',
      labelWidth : 55,
      frame : true,
      bodyStyle : 'padding:5px 5px 0',
      autoScroll : true,
      border : false,
      fileUpload : true,
      items : [{
            xtype : 'textfield',
            fieldLabel : '选择文件',
            name : 'userfile',
            inputType : 'file',
            allowBlank : false,
            blankText : '文件不能为空',
            height : 25,
            anchor : '90%'
          }],
      buttons : [{
        text : '上传',
        type : 'submit',
        handler : function() {
          if (!imgform.form.isValid()) {return;}
          imgform.form.submit({
            waitMsg : '正在上传',
            url : 'Default.aspx',
            success : function(form, action) {
              var element = document.createElement("img");
              element.src = action.result.fileURL;
              if (Ext.isIE) {
                editor.insertAtCursor(element.outerHTML);
              } else {
                var selection = editor.win.getSelection();
                if (!selection.isCollapsed) {
                  selection.deleteFromDocument();
                }
                selection.getRangeAt(0).insertNode(element);
              }
              win.hide();
            },
            failure : function(form, action) {
              form.reset();
              if (action.failureType == Ext.form.Action.SERVER_INVALID)
                Ext.MessageBox.alert('警告',
                    action.result.errors.msg);
            }
          });
        }
      }, {
        text : '关闭',
        type : 'submit',
        handler : function() {
          win.close(this);
        }
      }]
    })
    var win = new Ext.Window({
          title : "上传图片",
          width : 300,
          height : 200,
          modal : true,
          border : false,
          iconCls : "picture.png",
          layout : "fit",
          items : imgform
        });
    win.show();
  },
  createToolbar : function(editor) {
    HTMLEditor.superclass.createToolbar.call(this, editor);
    this.tb.insertButton(16, {
          cls : "x-btn-icon",
          icon : "picture.png",
          handler : this.addImage,
          scope : this
        });
  }
});
Ext.reg('StarHtmleditor', HTMLEditor);
页面js代码
Ext.onReady(function() {
  Ext.QuickTips.init();
  Ext.form.Field.prototype.msgTarget = 'side';
  var ff = new Ext.FormPanel({
        title : "文件上传",
        renderTo : document.body,
        width : 600,
        height : 480,
        labelWidth : 55,
        frame : true,
        items : [{
              xtype : "textfield",
              name : "title",
              fieldLabel : "标题",
              anchor : "98%"
            }, {
              xtype : "combo",
              name : "topic_id",
              fieldLabel : "所属栏目",
              anchor : "98%"
            }, {
              xtype : "textfield",
              name : "keywords",
              fieldLabel : "关键字",
              anchor : "98%"
            }, {
              xtype : "StarHtmleditor",
              name : "content",
              fieldLabel : "内容",
              anchor : "98%"
            }]
  });
});
后台代码简单实现了一下
protected void Page_Load(object sender, EventArgs e)
    {
      string fileName = string.Empty;
      string fileURL = string.Empty;
      string rt = string.Empty;
      try
      {
        HttpPostedFile file = Request.Files[0];
        fileName = GetFileName(file.FileName);
        file.SaveAs(Server.MapPath("upload//") + fileName);
        fileURL = "upload/" + fileName;
        rt = "{success:'true',fileURL:'" + fileURL + "'}";
      }
      catch
      {
        rt = "{success:'false',fileURL:'" + fileURL + "'}";
      } 
       
      Response.Write(rt);
    }
    
    private string GetFileName(string FullName)
    {
      string fileName = string.Empty;
      int last = FullName.LastIndexOf(@"/");
      fileName = FullName.Substring(last + 1, FullName.Length - last - 1);
      return fileName;
    }
实现效果如下

http://blog.csdn.net/zhaozhen1984/article/details/5911839
原文链接请查看谢谢。
http://www.cnblogs.com/wuliangbo/archive/2009/03/08/1406460.html
详查链接。谢谢。
