zoukankan      html  css  js  c++  java
  • Salesforce图片上传

    Salesforce图片上传的方式可通过自带组件apex:inputFile及html标签input type="file"实现。

    1、效果

    2、apex:inputFile实现

    采用标准组件inputFile并将值赋给页面变量(view state)Picture

    <apex:pageBlockSection columns="1">
    	<apex:inputFile value="{!Picture}" accept="image/*" />
    </apex:pageBlockSection>
    <apex:pageBlockButtons>
    	<apex:commandButton value="Save" action="{!save}" />
    </apex:pageBlockButtons>
    public with sharing class Test_HpcUploadImg {
    public blob Picture { get; set; }
    
    public PageReference save() {
    	ErrorMessage = '';
    	try {
    		if (picture != null) {
    			String url = CN_SPR_UploadAzureHelper.UploadToAzure(picture,'.jpg','application/octet-stream');
    			ErrorMessage=url;

    注意:

    此种方式图片大小限制为170KB,超过则提示“Maximum view state size limit (170KB) exceeded. Actual view state size for this page was 293.157KB”

    3、input type="file"实现

    <div class="slds-col slds-size_1-of-1 slds-p-horizontal_medium">
        <img id="imgPreview_csp" style="180px;height:180px;" src="{!URLFOR($Resource.India_Content, 'img/sample_picture.png')}" />
    </div>
    <div class="slds-col slds-size_1-of-1 slds-p-horizontal_medium" style="margin-top:5px;">
        <input type="file" id="fileImg_csp" value="" filename="fileImg_csp" style="display:none;" accept=".jpg,.jpeg,.png" />
        <button class="slds-button slds-button_neutral" id="btnSelecttPic" style="display:none;">Select a Picture</button>
        <input type="Button" value="Upload" id="btnSave_csp" class="slds-button slds-button_brand" style="display:none;" />
    </div>
    //选择图片,马上预览
    function changeImg(obj) {
        var file = obj.files[0];
        var reader = new FileReader();
    
        //读取文件过程方法
        reader.onloadstart = function (e) { //开始读取
        }
        reader.onprogress = function (e) { //正在读取中
        }
        reader.onabort = function (e) { //中断读取
        }
        reader.onerror = function (e) { //读取异常
        }
        reader.onload = function (e) { //成功读取
            var files = document.getElementById('fileImg_csp').files;
            var fileName = files[0].name;
            //判断文件后缀
            if (!(/.jpg$/.test(fileName) || /.jpeg$/.test(fileName) || /.png$/.test(fileName))) {
                Messages.add(Messages.Type.error, "JPG,PNG images only supported");
                return;
            }
            var img = document.getElementById("imgPreview_csp");
            img.src = e.target.result;
            //或者 img.src = this.result;  //e.target == this
        }
    
        reader.readAsDataURL(file);//必须要加
    }
    
    //上传
    function saveImg() {
        Messages.clear();
    
        var maxFileSize = 1572864;      //1.5M=1.5*1024*1024
        var attachmentBody;                //附件内容
        var attachmentName;                //附件名称
        var fileSize;                     //附件大小
    
        var Files = document.getElementById('fileImg_csp').files;
        var File = Files[0];
    
        if (File != undefined) {
            if (File.size <= maxFileSize) {
                attachmentName = File.name;
                //判断文件后缀
                if (!(/.jpg$/.test(attachmentName) || /.jpeg$/.test(attachmentName) || /.png$/.test(attachmentName))) {
                    Messages.add(Messages.Type.error, "JPG,PNG images only supported");
                    return;
                }
                // debugger;
                var fileReader = new FileReader();
                fileReader.readAsBinaryString(File);
                fileReader.onloadend = function (e) {
                    Spinner.show();
                    //原始对象
                    // attachmentBody = this.result;
                    //Base64(btoa用于将对象创建为base-64 编码的字符串)
                    attachmentBody = window.btoa(this.result);
                    //Base64编码转换为Blob
                    // attachmentBody=getBlob(window.btoa(this.result));
    
                    Visualforce.remoting.Manager.invokeAction(
                        '{!$RemoteAction.IN_ChillerStandardPicture_Controller.UploadPicture}',
                        attachmentName,
                        attachmentBody,
                        getQueryParams(),
                        function (result, event) {
                            Spinner.hide();
                            console.log(result);
                            // alert('Upload Successfully');
                            Messages.add(Messages.Type.info, "Upload Successfully");
                        });
    
                }
                fileReader.onerror = function (e) {
                    // alert("Upload failed");
                    Messages.add(Messages.Type.error, "Upload failed");
                }
                fileReader.onabort = function (e) {
                    // alert("Upload failed");
                    Messages.add(Messages.Type.error, "Upload failed");
                }
                fileReader.onload = function (e) {
    
                }
            } else {
                // alert("Maximum upload of 1.5M files is allowed");
                Messages.add(Messages.Type.error, "Maximum upload of 1.5M files is allowed");
            }
        } else {
            // alert("Please select a file first");
            Messages.add(Messages.Type.error, "Please select a file first");
        }
    }
    //上传图片
    @RemoteAction
    public static String UploadPicture(String attachmentName,String attachmentBody,String queryParam) {
        try {
            //反序列化
            IN_AvailablilityAbi_Controller.QueryRequestParam req = (IN_AvailablilityAbi_Controller.QueryRequestParam)JSON.deserialize(queryParam, IN_AvailablilityAbi_Controller.QueryRequestParam.class);
    
            //上传图片到Azure
            // Blob blobFile= Blob.valueOf(attachmentBody);//将Base64编码的字符串转换为Blob【此处有问题】
            Blob blobFile = EncodingUtil.base64Decode(attachmentBody);//将Base64编码的字符串转换为Blob
            string fileSuffix= attachmentName.substring(attachmentName.indexOf('.'));//后缀
            String url = CN_SPR_UploadAzureHelper.UploadToAzure(blobFile,fileSuffix,'application/octet-stream');

    注意:

    此种方式测试了1.7M的图片可正常上传,5M则提示超出了大小限制(具体限制大小需再做测试)

    4、建议

    建议采用input type="file"实现的方式,且将图片以Base64传输到后端再进行流的转换。如果在前端进行Blob的转换需要考虑后端接收流的方式。

    JS将Base64编码转换为Blob的实现如下:

    //Base64编码转换为Blob
    function getBlob(text) {
     var buffer = new Uint8Array(text.length);
     var pecent = 0, loop = null;
     for (var i = 0; i < text.length; i++) {
         buffer[i] = text.charCodeAt(i);
     }
     var format = 'image/jpeg';
    
     try {
         return new Blob([buffer], { type: format });
     } catch (e) {
         var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
         buffer.forEach(function (buf) {
             bb.append(buf);
         });
         return bb.getBlob(format);
     }
    }
  • 相关阅读:
    Windows 2003/2008更改远程桌面端口脚本
    如何修改远程桌面连接3389端口
    关于百度地图(离线)使用过程报“Cannot read property 'jb' of undefined ”错误的解决办法
    IIS 错误:处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler”
    IIS 错误:由于扩展配置问题而无法提供您请求的页面。如果该页面是脚本,请添加处理程序。如果应下载文件,请添加 MIME 映射。
    IIS7错误:不能在此路径中使用此配置节。如果在父级别上锁定了该节,便会出现这种情况。锁定是默认设置的(overrideModeDefault="Deny")......
    Jqgrid pager 关于“local” dataType 动态加载数据分页的研究(没好用的研究结果)
    JQGrid导出Excel文件
    Oracle以15分钟为界,统计一天内各时间段的数据笔数
    ORA-01438: 值大于为此列指定的允许精度
  • 原文地址:https://www.cnblogs.com/hepc/p/10891711.html
Copyright © 2011-2022 走看看