• 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);
     }
    }
  • 相关阅读:
    暑假集训每日一题0716(BFS)
    HDOJ1754(I Hate It)
    POJ2777(Count Color)
    暑假集训每日一题0717(DFS)
    SPOJ7259(Light Switching)
    cocos2dx CCTextureCache
    写给自己——EntryName命名规则
    观XX项目感1
    观XX项目感2 之 软件工程的图纸(再看UML类图)
    游戏编程 && cocos2d 学习
  • 原文地址:https://www.cnblogs.com/hepc/p/10891711.html
Copyright © 2020-2023  润新知