我有一个使用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;
};
服务器按照如下方式接收请求,并将二进制数据保存在DB 中
@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匹配,但我怎么才能正确呢?
我发现了问题。
我更改上传文件代码如下:
// 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)
}