0

由于服务器问题,我需要在将文件上传到服务器之前将其内容转换为 Base64。

我已经使用 reader.readAsDataURL 管理了 JS 方面的内容,以将内容放入本地 JS 变量中的 Base64 中。然后我尝试创建一个新的 FormData 并在那里设置 base64 变量 - 它替换了名称,但随后它也替换了类型 - 它不再是二进制数据,而只是二进制数据 - 所以当我将它发送到服务器时 - 我m 得到 Spring 错误 typeMismatch.org.springframework.web.multipart.MultipartFile

基本上 - 任何想法如何将文件内容转换为 Base64(完成)但使用 Spring MultiPartFile 发送到现有的 JAVA 方法?

即无需我重写并在FormData 中添加额外的字段以获取文件名和大小等(我在服务器端使用MultipartFile 得到的东西)。JS:(删除错误处理)

var input = $(".actualFileInput");
var files = null;
// File data
if (input[0].files.length > 0) {
    files = input[0].files;
}
var file = files[0], reader = new FileReader();
            
reader.onloadend = function () {
    var b64 = reader.result.replace(/^data:.+;base64,/, '');
    var name = input.attr('name');
    input.attr('name', '');
                
    var newFormData = new FormData(form);   // New form with all data from the existing one
    newFormData.set('uploadFile',b64);  // replace with the base64 value of the selected file
    var request = new XMLHttpRequest();
                
    request.onreadystatechange = function () {
        request.open(form.method, form.action, true);
        request.onload = function() {
            var url = window.location;
            input.attr('name', name);   
            request.send(newFormData);
                
    };
reader.readAsDataURL(file);

服务器端的Java:

@RequestMapping(method = RequestMethod.POST, params = "upload")
public String upload(@ModelAttribute("uploadDocument") UploadDocument document, BindingResult result,
        ModelMap model, HttpServletRequest request, SessionStatus status) throws Exception {

上传文件是:

公共类 UploadDocument 实现 Serializable {

private static final long serialVersionUID = -3534003705995293025L;

// File upload work area
private MultipartFile   uploadFile = null;
private String          fileComment = null;
private Integer         fileTypeId = null;
... (other fields in the <form>)

如果我只是提交表单,所有的 JAVA 东西都可以正常工作。但是在 JS 中以 Base64 格式读取文件内容,然后作为字段发送不会被转换为 MultiPartFile。更改为 byte[] 并自己为文件元数据添加新字段?还是我缺少一些技巧。

谢谢各位。

4

1 回答 1

0

让这个 JS 变量发送到 Spring MultiPartFile 的方法是:

newFormData.set('uploadFile',new Blob([b64]),files[0].name); //替换为所选文件的base64值

即使它成为一个blob,第三个参数是用户在. 这现在发送文件内容的 base64 值。

于 2020-11-25T22:42:21.187 回答