问题
i want to send formdata to server with fileTransfer(ionic 3 ) or other function
var form = new FormData();
form.append("filedata", base64File);
form.append("numDeclaration", "01012018");
let options: FileUploadOptions = {
fileKey: 'filedata',
fileName: imageName,
chunkedMode: false,
mimeType: "image/jpeg",
headers: {}
}
fileTransfer.upload(base64File, 'http://localhost:8080/alfresco/api/-default-/public/alfresco/versions/1/nodes/f3589d6b-82db-44d2-9b6d-89a3e7e57442/children?alf_ticket=' + localStorage.getItem('token'), options).then((data) => {
console.log(data + " Uploaded Successfully");
}
回答1:
I think it’s not necessary to use cordova file transfer plugin in your case. You can just send FormData through angular HttpClient (XMLHttpRequest). You just need to convert base64 string into blob object which you can to upload further on your server.
class UploadService {
constructor(private httpClient: HttpClient) {
const base64 = 'data:image/png;base64,';
this.uploadBase64(base64, 'image.png').subscribe(() => {});
}
uploadBase64(base64: string, filename: string): Observable<any> {
const blob = this.convertBase64ToBlob(base64);
const fd = new FormData();
fd.append('filedata', blob, filename);
fd.append('numDeclaration', '01012018');
return this.httpClient.post('url', fd)
.pipe(catchError((error: any) => Observable.throw(error.json())));
}
private convertBase64ToBlob(base64: string) {
const info = this.getInfoFromBase64(base64);
const sliceSize = 512;
const byteCharacters = window.atob(info.rawBase64);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
byteArrays.push(new Uint8Array(byteNumbers));
}
return new Blob(byteArrays, { type: info.mime });
}
private getInfoFromBase64(base64: string) {
const meta = base64.split(',')[0];
const rawBase64 = base64.split(',')[1].replace(/\s/g, '');
const mime = /:([^;]+);/.exec(meta)[1];
const extension = /\/([^;]+);/.exec(meta)[1];
return {
mime,
extension,
meta,
rawBase64
};
}
}
回答2:
I got into the same problem, and did not wanted to use ionic file transfer plugin.
I read the file as blob and added that in formData. Worked fine for me.
private fileReader(file: any) {
const reader = new FileReader();
reader.onloadend = () => {
const formData = new FormData();
const blobFile = new Blob([reader.result], { type: file.type });
formData.append("file", blobFile, "filename");
// POST formData call
};
reader.readAsArrayBuffer(file);
}
回答3:
You can not send formdata using fileTransfer API. If you want to pass additional data along file object you can use params key inside FileUploadOptions.
回答4:
I had a problem when uploading an image to azure blob storage so after speding quite a bit of time on this I came out with this solution. It has logic for pc and android/ios separated as they work differently. Please take a look at the code below.
send to blob storage
if (Capacitor.platform === 'ios' || Capacitor.platform === 'android') {
const blob = this.base64ToBlob(file);
const fileToUpload = blob;
const xhr = new XMLHttpRequest();
xhr.open('PUT', path);
xhr.onload = () => {
console.log('sent to azure blob storage');
};
xhr.setRequestHeader('x-ms-blob-type', 'BlockBlob');
xhr.setRequestHeader('Content-Type', 'image/jpeg');
xhr.send(fileToUpload);
} else { // PC
this.http.put(path, file, {
headers: new HttpHeaders({
'x-ms-blob-type': 'BlockBlob',
'Content-Type': 'image/jpeg',
'x-ms-blob-content-type': file.type,
'X-Skip-Interceptor': ''
})
}).subscribe(() => {
console.log(`APP: ${fileName} uploaded to blob storage`);
});
}
base64ToBlob function
-> https://stackoverflow.com/a/16245768/5232022
base64ToBlob(file) {
let b64Data = file.base64Image;
const contentType = 'image/jpeg';
const sliceSize = 512;
b64Data = b64Data.replace(/data\:image\/(jpeg|jpg|png)\;base64\,/gi, '');
const byteCharacters = atob(b64Data); // decode base64
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
}
来源:https://stackoverflow.com/questions/50238720/how-to-use-formdata-for-ionic-file-upload