【问题标题】:Converting <input type=file> contents to Base64 and sending to Spring method expecting MultiPartFile将 <input type=file> 内容转换为 Base64 并发送到期望 MultiPartFile 的 Spring 方法
【发布时间】:2021-03-08 01:46:38
【问题描述】:

由于服务器问题,我需要在上传文件到服务器之前将其内容转换为 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 实现可序列化 {

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[] 并自己为文件元数据添加新字段?还是我缺少一些技巧。

谢谢各位。

【问题讨论】:

    标签: javascript base64 multipartfile


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-31
      • 2022-11-09
      • 2021-09-05
      • 2013-01-29
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多