如何上传JavaScript blob而不将其转换为base64字符串?

问题描述 投票:0回答:1

我已经在js中将音频录制为blob,那么如何在不将其转换为base64字符串并通过

<p:remoteCommand>
<h:commandScript>
发送的情况下上传它?

jsf primefaces
1个回答
0
投票

使用被CSS隐藏的

<h:inputFile>
并让
<h:commandScript>
(或
<p:remoteCommand>
)也处理/执行它。

<h:form id="form" enctype="multipart/form-data">
    <h:inputFile id="file" value="#{bean.uploadedFile}" styleClass="ui-helper-hidden" />
    <h:commandScript name="hiddenUpload" action="#{bean.upload}" execute="@form" />
</h:form>
private Part uploadedFile; // +getter+setter

public void upload() throws IOException {
    byte[] blob = uploadedFile.getInputStream().readAllBytes();
    // ...
}

您可以在 JS 中使用

DataTransfer
API 来设置
<input type="file">
Blob
的值。假设您的音频 blob 由
yourAudioBlob
变量表示,下面是一个示例:

const fileBlob = yourAudioBlob;
const fileName = "yourFileName.mp3";
const fileOptions = { type: "audio/mpeg", lastModified: new Date().getTime() };
const file = new File([fileBlob], fileName, fileOptions);
const dataTransfer = new DataTransfer(); 
dataTransfer.items.add(file);
document.getElementById("form:hiddenFile").files = dataTransfer.files;
hiddenUpload();
© www.soinside.com 2019 - 2024. All rights reserved.