界面上添加以及编辑图片

新增的js代码:

控件代码。。

   var PhotoBox ={
        xtype: 'box',
        id : 'logoPic',
        width : 180,
        height : 210,
        autoEl : {
            tag : 'img',
            style : 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);'
        }
    };

    //图片路径获取
    this.PhotoLogic={
        name:"upload",
        xtype:'textfield',
        id: 'logoFile',
        inputType:'file',
        labelStyle:"width:80px",
        fieldLabel:'获取本地图片',
//       blankText:'请上传图片',
        width:140,
        listeners :{
            'render':function(){
                var uploadlogoFileCmp = Ext.get('logoFile');
                uploadlogoFileCmp.on('change',function(field,newValue,oldValue){
                    this.FileName = uploadlogoFileCmp.getValue();
                    var url = 'file:///' + this.FileName;
                    if(Ext.isIE){
                        var  image = Ext.get('logoPic').dom;
                        image.src = Ext.BLANK_IMAGE_URL;
                        image.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = url;
                    }
                    else{
                        try{
                            Ext.get('logoPic').dom.src =Ext.get('logoFile').dom.files.item(0).getAsDataURL();
                        }catch(err){//getAsDataURL在Firefox7.0 无法预览本地图片
                            Ext.get('logoPic').dom.src = window.URL.createObjectURL(Ext.get('logoFile').dom.files[0]);
                        }
                    }
                },this);
            }
        }
    };
  var rightColumn = {
        id:"fileUploadForm",
        layout: 'form',
        columnWidth: .3,
        baseCls:"x-plain",
        items: [
            PhotoBox,
            this.PhotoLogic,
            this.lblstate
        ]//,

Add时的请求,因为其他一些数据也要存储,因此,是先去存储图片并把图片的key返回回来,然后去存储其他的数据以及这个key,两个AJAX请求

  AddFunction:function(){
        var img_reg = /\.([jJ][pP][gG]){1}$|\.([jJ][pP][eE][gG]){1}$|\.([gG][iI][fF]){1}$|\.([pP][nN][gG]){1}$|\.([bB][mM][pP]){1}$/

        if (this.form.getForm().isValid()) {
//            Ext.MessageBox.show({
//                msg: resourceSavingHint,
//                progressText: 'Saving...',
//                width: 300,
//                wait: true,
//                waitConfig: { interval: 200 },
                icon: 'upload',
//                animEl: 'saving'
//            });
            setTimeout(function () { }, 1000);
            this.form.getForm().submit({
                url:$("#ctx").val() + "/purview/driver/addImage.action",//请求获得那个key
                method: "POST",
                success : function(data, optc) {
                   var result = Ext.decode(optc.response.responseText)
                    if(result.keyImage!=null){
                       this.keyImage=result.keyImage;
                    }
                    //新增                


                    this.DriverName = this.txt_DriverName.getValue().trim();
                    this.DriverNo = this.txt_DriverNo.getValue().trim();
                    this.Groupadd = this.combo_Groupadd.value;
                    this.Sex = this.combo_Sex.value;
                    this.LicenceType = this.combo_LicenceType.value;
                    this.DriverLic = this.txt_DriverLic.getValue().trim();
                    this.ValidPeriod = this.combo_ValidPeriod.value;
                    this.InValidTime = this.txt_InValidTime.getValue().format('Y-m-d');
                    this.Password = this.txt_Password.getValue();
                    this.UseState = this.UseStateRadioCheck.getValue().inputValue;
                    this.FileName = Ext.getCmp("logoFile").getValue();
                    this.IdentityCartNO = this.txt_IdentityCartNO.getValue().trim();
                    this.QualificationCerNO = this.txt_QualificationCerNO.getValue().trim();
                    this.IssueAgencyName = this.txt_IssueAgencyName.getValue().trim();
                    this.Phone = this.txt_Phone.getValue().trim();
                    this.Address = this.txt_Address.getValue().trim();

                    //2014.4.22 新增
                    this.birth=this.txt_brith.getValue();
                    this.officeTel=this.txt_officeTel.getValue().trim();
                    this.issueDate=this.txt_issuDate.getValue();
                    this.homeTel=this.txt_HomeMobile.getValue().trim();
                    this.vehTeamId=this.combo_BelongCarList.value;

                    Ext.MessageBox.show({
                        msg: resourceSavingHint,
                        progressText: 'Saving...',
                        width: 300,
                        wait: true,
                        waitConfig: { interval: 200 },
                        icon: 'download',
                        animEl: 'saving'
                    });
                    setTimeout(function() { }, 300);

                    Ext.Ajax.request({//ajax请求存储其他数据
                        url:$("#ctx").val() + "/purview/driver/addDriver.action",
                        method: "POST",
                        params: { name: this.DriverName, no: this.DriverNo, groupId: this.Groupadd, gend: this.Sex,
                            licType: this.LicenceType, lic: this.DriverLic, validPeriod: this.ValidPeriod,
                            inValidDate: this.InValidTime,
                            pwd: this.Password,
                            curState: this.UseState,
                            idCard: this.IdentityCartNO, identCard: this.QualificationCerNO,
                            identQrg: this.IssueAgencyName,
                            mobile: this.Phone, addr: this.Address,
                            keyImage:this.keyImage,//this.FileName,
                            //2014.4.22 add
                            birth:this.birth,
                            officeTel:this.officeTel,
                            issueDate:this.issueDate,
                            homeTel:this.homeTel,
                            vehTeamId:this.vehTeamId //所属车队id

                        },
                        success: this.DriverAddSecess.createDelegate(this),
                        failure: function(form, action)
                        {
                            Ext.MessageBox.alert("提示","新增失败");
                        }
                    });
                }.createDelegate(this),
                failure : function(form, action) {
                    alert("failure");
                }
            });
         }
    }

java代码:

将图片存储在服务器上,并返回key,获得key值

@Controller
public class UploadImageAction extends BaseAction {
   private static Logger logger = LoggerFactory.getLogger(UploadImageAction.class);
    @Value("#{configProperties['fss.url']}")//URL地址
    private String fssUrl;
    private RestTemplate restTemplate = new RestTemplate();
    private ObjectMapper objectMapper = new ObjectMapper();

    private Boolean success = true;
    private Integer flag = 0;
    private String retMsg;
    private String exceptionMsg;
    private Byte rc;
    private String keyImage;


    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public Integer getFlag() {
        return flag;
    }

    public void setFlag(Integer flag) {
        this.flag = flag;
    }

    public String getRetMsg() {
        return retMsg;
    }

    public void setRetMsg(String retMsg) {
        this.retMsg = retMsg;
    }

    public String getExceptionMsg() {
        return exceptionMsg;
    }

    public void setExceptionMsg(String exceptionMsg) {
        this.exceptionMsg = exceptionMsg;
    }

    public Byte getRc() {
        return rc;
    }

    public void setRc(Byte rc) {
        this.rc = rc;
    }



    public String getKeyImage() {
        return keyImage;
    }

    public void setKeyImage(String keyImage) {
        this.keyImage = keyImage;
    }


   private File upload;// uplaod即js代码中的控件的id 其他的ContentType和FileName是固定的,就是这个名称+ContentType和FileName
  
  
private String uploadContentType; private String uploadFileName; //fileName 前面必須和uplaod一致,不然找不到文件即js代码中的控件的id @JSON(serialize = false) public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } @JSON(serialize = false) public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } @JSON(serialize = false) public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } // private static final int BUFFER_SIZE = 16 * 1024; /** * action 方法 */ public String addImage() { try { Date d = new Date(); this.uploadFileName=uploadFileName; this.uploadContentType=uploadContentType; String GuidStr; GuidStr=d.getTime()+getFileExp(this.uploadFileName); //key //upload -- wapps 下面的文件夹,用来存放图片 String toSrc = this.request.getSession().getServletContext().getRealPath("UploadFile")+"/"+d.getTime()+getFileExp(this.uploadFileName); //使用時間戳作為文件名 File toFile = new File(toSrc); String keyTemp = this.writeFile(GuidStr,this.upload); if(keyTemp!=null){ this.keyImage = keyTemp; } } catch (Exception e) { logger.error("uploadImage: {}", e.getMessage(), e); retMsg = "业务服务器异常!"; flag = 1; exceptionMsg = e.getMessage(); } return Action.SUCCESS; } //调用方法 返回key private String writeFile(String key, File file){ try { MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>(); parts.add("key", key); parts.add("file", new FileSystemResource(file)); String res = restTemplate.postForObject(fssUrl + "/upload", parts, String.class); Map r = objectMapper.readValue(res, Map.class); int code = ((Number)r.get("code")).intValue(); if (code != 0) { throw new Exception("[" + code + "] " + r.get("msg")); } return key; } catch (Exception e) { //throw new IOException("往文件服务器上传文件异常", e); e.printStackTrace(); } return null; } // 上传文件的文件名 private String getFileExp(String name) { int pos = name.lastIndexOf("."); return name.substring(pos); }
struts.xml配置

 <action name="addImage" class="com.yaxon.vn.portal.web.action.driver.UploadImageAction"
                method="addImage">
         <!--   <interceptor-ref name="fileUpload">
                <!–拦截器strut2自带的, 指定上传文件的格式,如果不符合规定,将会自动拦截下来 –>
                <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/jpg</param>
                <param name="maximumSize">20000000000</param>
            </interceptor-ref>-->
            <!-- <interceptor-ref name="defaultStack" /> -->
            <result name="success" type="json">
                <param name="contentType">text/html;charset=utf-8</param>
            </result>
        </action>



编辑的时候,从后台获得相应的fssUrl,

然后在控件中,box的控件中加个src,src是获得的服务器地址+图片KEY

this.PhotoBox ={
        xtype: 'box',
        id : 'logoPic',
        width : 180,
        height : 190,
        autoEl : {
            tag : 'img',
            style : 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);'  ,
            src:this.record.data.fssUrl+this.record.data.photo  //设置URL地址
        }
    };

网上看到其他人的方法:

网址:http://blog.csdn.net/youlianying/article/details/5065101 

Extjs并没有提供直接的组件来显示图片。网上通过设置textfield的InputType为Image然后再修改dom对象来实现,其实image的属性值并没有包含在Extjs的官方文档当中。可以通过以下的思路实现,更可以进一步扩展成自定义组件。推荐的方法如下:

1、首先做一个容器

Js代码  复制代码
  1. {   
  2.     xtype: 'box'//或者xtype: 'component',   
  3.     width: 100, //图片宽度   
  4.     height: 200, //图片高度   
  5.     autoEl: {   
  6.         tag: 'img',    //指定为img标签   
  7.         src: 'myphoto.gif'    //指定url路径   
  8.     }   
  9. }  
[js]  view plain copy
  1. {  
  2.     xtype: 'box'//或者xtype: 'component',  
  3.     width: 100, //图片宽度  
  4.     height: 200, //图片高度  
  5.     autoEl: {  
  6.         tag: 'img',    //指定为img标签  
  7.         src: 'myphoto.gif'    //指定url路径  
  8.     }  
  9. }  

 这样就在panel或者其他的容器里面显示图片了

2、图片的动态更新

 

Java代码  复制代码
  1. //动态更新只需要获取到刚才建立的box的dom的src   
  2. myphoto.getEl().dom.src = newSrc  

      这样是错误的

        myphoto.autoEl.src=newSrc


但是我在show时尝试发现读不到getEl()

另外,因为从后台Action返回的没有URL地址,那么,在返回的list即store中也没,这样,在相应的Action中注入URL地址,同时在list里循环每个对象都加这么个属性

(类中要有该fssUrl属性,进行get和set方法)

  driverVoList = fetchDriverRes.getDriverVoList();
           for(DriverVo vo:driverVoList){
               vo.setFssUrl(fssUrl);
           }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值