buli
2022-03-10 a90c9ecfc5118547d0a92b2fee2779eca95e09a5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
<!-- 该页面用于Lead对象上传PDF,未来如果要添加其他对象的上传PDF功能,复制该页面,将**standardController**修改为其他对象API名称即可 -->
<apex:page standardController="Consum_Apply__c" extensions="FileUploadController" id="page" lightningStyleSheets="true">
    <apex:includeScript value="{! URLFOR($Resource.AWSService, 'AWSService.js') }" />
    <script>
        var staticResources = JSON.parse('{!staticResource}');
        var parentId = '{!parentId}';
        var uploadUrl = staticResources.newUrl;
        var key;
 
        function alertErrorMessage(errorMsg) {
            let errorMsgNode = document.getElementById("page:theForm:block:msgContent");
            errorMsgNode.innerText = errorMsg;
            errorMsgNode.className = 'message errorM3';
        }
 
        function hiddenErrorMsgNode() {
            let errorMsgNode = document.getElementById("page:theForm:block:msgContent");
            errorMsgNode.innerText = '';
            errorMsgNode.className = '';
        }
        function getFileContent(event) {
            var fileObject = document.getElementById("page:theForm:block:uploadSection:file");
            var reader = new FileReader();
            var data = reader.readAsDataURL(fileObject.files[0]);
            debugger
            console.log(event);
        }
        function getBase64(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            });
        }
        function disableButtonStatus() {
            let btnNode = document.getElementById('uploadFileId');
            btnNode.classList.add("btnDisabled");
        }
 
        function enableButtonStatus() {
            let btnNode = document.getElementById('uploadFileId');
            btnNode.classList.remove("btnDisabled");
        }
 
        function uploadFile() {
            disableButtonStatus();
            var fileObject = document.getElementById("file").files[0];
            getBase64(fileObject).then(
                data => {
                    console.log(data);
                    uploadFileToAWS(data, (fileObject.size).toString(), fileObject.name);
                    
                }
            );
        }
        function confirmTrans(transId, isSuccess) {
            
            fetch(staticResources.updateUrl, {
                method: 'POST',
                body: JSON.stringify({ 'txId': transId, "isSuccess": isSuccess }),
                headers: {
                    'Content-Type': 'application/json',
                    'pi-token': staticResources.token
                }
            }).then((data) => {
                return data.json();
            }).then(data => {
                console.log("confirmTrans-" + JSON.stringify(data));
                document.getElementById("file").files[0].name = '';
                enableButtonStatus();
                refreshFiles();            
                return data.status;
            })
            
        }
        function calculateFileSize(fileObject) {
            if (fileObject.size > 20971520) {
                alertErrorMessage('文件过大,请选择小于20mb的文件');
            }
        }
        function uploadFileToAWS(data, size, fileName) {
            console.log("body=" + JSON.stringify({ 'file': data, "size": size, 'fileName': fileName }));
            
            fetch(uploadUrl, {
                method: 'POST',
                body: JSON.stringify({ 'file': data, "size": size, 'fileName': fileName }),
                headers: {
                    'Content-Type': 'application/json',
                    'pi-token': staticResources.token
                }
            }).then((data) => {
                return data.json();
            }).then(result => {
 
                console.log("result" + JSON.stringify(result));
                
                if (result.success == true) {
                    key = result.object;
 
                    Visualforce.remoting.Manager.invokeAction(
                        '{!$RemoteAction.FileUploadController.saveFile}',
                        fileName, key, result.txId, parentId,
                        function (resultvalue, event) {
 
 
                            
                            //2. show file list
                            if (resultvalue.status == 'fail') {
                                alertErrorMessage(resultvalue.message);
                                //1. Confirm trans
                                confirmTrans(result.txId, 0);                              
                            } else {
                                alertErrorMessage('上传成功');
                                confirmTrans(result.txId, 1);
                            }
                            
                            // window.location.reload();
                        },
                        { escape: true }
                    );
                   
                    console.log('key' + key);
                } else {
                    alertErrorMessage('上传失败请稍后再试!');
                }
            }).catch((error) => {
                console.error('Error:', error);
            })
            debugger
        }
        function downPdf(fileUrl) {
            window.open(fileUrl,'_blank');
        }
 
    </script>
    <style>
        .pdf .num {
            width: 30%;
        }
 
        .pdf.name {
            width: 30%
        }
 
        .pdf.downLink {
            width: 40%
        }
    </style>
    <apex:form id="theForm">
        <apex:actionFunction name="refreshFiles" action="{!refreshFiles}" reRender="pdf,uploadSection"/>      
        <br/>
        <br/>
        <apex:pageBlock id="block">
            <div style="text-align: center;">
                <apex:outputPanel id="errorMsg">
                    <apex:pageMessages id="msgContent" escape="false" />
                </apex:outputPanel>
            </div>
            <apex:pageBlockSection id="uploadSection">
                <!-- <apex:inputFile id="file" value="{!documentData.body}" filename="{!documentData.name}" /> -->
                <input type="file" id="file" name="filename"/>
                <input class="btn" id='uploadFileId' type="Button" value="确认上传" onclick="uploadFile()" />
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock title="PDF列表" id="pdf">
            <!-- <apex:pageBlockSection > -->
            <!-- show uploated file list -->
            <apex:pageBlockTable value="{!fileList}" var="file" align="center" columns="3" columnsWidth="30%,30%,40%">
                <apex:column id="name" headerValue="文件名称">
                    <apex:outputLink value="/{!file.Id}" target="_blank">{!file.FileName__c}</apex:outputLink>
                </apex:column>
                <!-- <apex:column id="num" headerValue="父记录链接">
                    <apex:outputLink value="/{!file.ParentRecordId__c}" target="_blank">{!file.ParentRecordId__c}</apex:outputLink>
                </apex:column> -->
                <apex:column id="previewLink" headerValue="预览链接">
                    <apex:outputLink value="{!file.ViewLink__c}" target="{!file.ViewLink__c}">预览链接
                    </apex:outputLink>
                </apex:column>
                <apex:column id="downLink" headerValue="下载链接">
                    <!-- <apex:outputLink value= "{!file.DownloadLink__c}" target="{!file.DownloadLink__c}">下载链接
                    </apex:outputLink> -->
                    <input class="btn" id='downloadFileButton' type="Button" value="下载" onclick="downPdf('{!file.DownloadLink__c}')" />
                </apex:column>
            </apex:pageBlockTable>
            <!-- </apex:pageBlockSection> -->
        </apex:pageBlock>
    </apex:form>
 
</apex:page>