Salesforce圖片上傳

Salesforce圖片上傳的方式可經過自帶組件apex:inputFile及html標籤input type="file"實現。html

一、效果前端

二、apex:inputFile實現後端

採用標準組件inputFile並將值賦給頁面變量(view state)Pictureapp

<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;

注意:ide

此種方式圖片大小限制爲170KB,超過則提示「Maximum view state size limit (170KB) exceeded. Actual view state size for this page was 293.157KB」oop

 

三、input type="file"實現測試

<div class="slds-col slds-size_1-of-1 slds-p-horizontal_medium">
    <img id="imgPreview_csp" style="width: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');

注意:ui

此種方式測試了1.7M的圖片可正常上傳,5M則提示超出了大小限制(具體限制大小需再作測試)this

 

四、建議編碼

建議採用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); } }
相關文章
相關標籤/搜索