首页 > 解决方案 > 使用 Angularjs/Spring 上传/下载 uint8array

问题描述

我有一个使用 Angularjs 作为前端的 Spring 应用程序。

在前端,我读取了一个使用 Openpgpjs 编码的文件。在加密过程之后,我得到了一个我想保存到数据库的 Uint8Array 对象。

// encoded_file is the Uint8Array
var file = new File(encoded_file, "my_image.png",{type:"image/png", lastModified:new Date()})

FileService.uploadFile(file).then(function(fileObject){
    console.log(fileObject); 
}).catch(function(error){
    toastrService.error(error, "Failed to upload file"); 
});


this.uploadFile=  function (file) {
    var defer = $q.defer();
    var fd = new FormData();
    fd.append('file', file);
    fd.append('auth', true);
    
    $http.post('/files/upload', fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).then(function (response) {
        if (response.data && response.data.result){
            defer.resolve(response.data.entry);
        } else if(response.data) {
            defer.reject(response.data.message);
        } else {
            defer.reject();
        }
    }, function (error) {
        defer.reject(error);
    });
    
    return defer.promise;
};

服务器接收请求如下,将二进制数据保存在数据库中

@RequestMapping(method = RequestMethod.POST, value = "/upload")
public String uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("auth") Optional<Boolean> auth) throws Exception {
       // save file.getBytes() in the DB and return a uniqueID to the file
}

该文件可通过 url /files/raw/id 在我的应用程序中访问

@RequestMapping(path = "/raw/{fileId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody byte[] getRawFile(@PathVariable String fileId, HttpServletResponse response) throws Exception {
    File f = fileService.getFile(fileId);
    if (f == null) {
        return null;
    }

    return fileService.getFileContent(f);

}

我有以下功能来下载文件

this.downloadFile=  function (guid) {
    var defer = $q.defer();
    var config = { responseType: 'arraybuffer' };
    $http.get('/files/raw/'+guid, config).then(function (response) {
        console.log(response)
        if (response && response.data){

           defer.resolve(response.data); 
        } else {
            defer.reject();
        }
    }, function (error) {
        defer.reject(error);
    });
    
    return defer.promise;
};

问题是我下载文件时得到的 Uint8array 与我上传的不同。如果我将 responseType 更改为文本。该数字与我上传的 uint8array 匹配,但我怎样才能正确?

标签: angularjsspring-mvcuint8array

解决方案


我发现了问题。

我将上传文件代码更改如下:

// encoded_file is the Uint8Array
 var blob = new Blob([encoded_file.buffer], {type: $file.type});
 var file = new File([blob], $file.name);

FileService.uploadFile(file).then(function(fileObject){
    console.log(fileObject); 
}).catch(function(error){
    toastrService.error(error, "Failed to upload file"); 
});

下载功能如下:

var fileReader = new FileReader();
fileReader.onload = function(event) {
      arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(file.data);
fileReader.onloadend = function (e) { 
     var data = new Uint8Array(arrayBuffer) 
                    
}

推荐阅读