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
詳查鏈接。謝謝。
