问题描述
我有一个使用 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 相匹配,但我怎样才能正确?
解决方法
我发现了问题。
我将上传文件代码更改如下:
// 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)
}