Ker*_* Hu 12 file-upload typescript angular
我想在同一个请求中实现post文件和Json数据.
以下是上传文件代码:
upload(url:string,file:File):Observable<{complate:number,progress?:number,data?:Object}>{
return Observable.create(observer => {
const formData:FormData = new FormData(),
xhr:XMLHttpRequest = new XMLHttpRequest();
formData.append('uploadfile', file);
formData.append("_csrf", this.tokenService.getCsrf());
xhr.open('POST',url, true);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next({complate:1,progress:100,data:JSON.parse(xhr.response)});
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
observer.next({complate:0,progress:Math.round(event.loaded / event.total * 100)});
};
const headers=new Headers();
let token: string = localStorage.getItem('access-token');
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
xhr.send(formData);
}).share();
Run Code Online (Sandbox Code Playgroud)
如何与angular2 http.post(url,JSON.stringify(data))集成.
所以我一直在努力做到这一点,对于看起来非常简单的事情,我最终找到了解决方案的麻烦.希望有些同事帮助我,我们想出了一些合理的东西.
这个文档帮助了我们很多:https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
这是Angular代码:
class SomeService {
someMethod(fileToUpload: File, name: string, version: string) {
const formData: FormData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
const overrides = {
name,
version,
};
const blobOverrides = new Blob([JSON.stringify(overrides)], {
type: 'application/json',
});
formData.append('overrides', blobOverrides);
const req = new HttpRequest('POST', `some-url`, formData);
return this.http.request(req);
}
}
Run Code Online (Sandbox Code Playgroud)
正如@Supamiu所说,使用Blob是关键,这是一个如何做到这一点的例子.
下面的客户端和服务代码在我的解决方案中工作正常,检查这是否有帮助
客户端代码:
AddModelData(modelData: ModelData, file: any): Observable<any>
{
let urlPath = 'api/SampleActionMethod/AddModelData';
const mData = JSON.stringify(modelData);
const formData = new FormData();
formData.append('data', mData);
if (file) {
formData.append('file', file, file.name);
}
return this._http.post(this.settings.apiEndPoint + urlPath, formData);
}
Run Code Online (Sandbox Code Playgroud)
服务端代码:
public IActionResult PostMethod(IFormFile file)
{
try
{
var modelData = JsonConvert.DeserializeObject<ModelData>(Request.Form["data"]);
//data is the key that is being passed from client side
//file in params will have the posted file
//Do Something with data and file......
return Ok();
}
catch (Exception e)
{
return StatusCode(500, e.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
//app.component.html
<input type="file" name="file" (change)="onChange($event)">
<button (click)="onSubmisson()" [disabled]="file==null" >Submit</button>
//app.component.ts
file:File = null;
onChange(event){
this.file = event.target.files[0]
}
onSubmisson(){
this._auth.uploadFileAndData(this.file).subscribe(
res => {
console.log(res);
},err => {
console.log(err);
});
}
//upload.service.ts
uploadFileAndData(file){
var test = {test:"test"}
const formData = new FormData();
formData.append('data', JSON.stringify(test));
formData.append('file', file, file.name);
return this._http.post<any>(this._uploadurl, formData);
}
//node server
var multer = require('multer');
var path = require('path');
var storage = multer.diskStorage({
// destination
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({ storage: storage }).array("file", 12);
router.post("/upload", function(req , res){
upload(req, res, function (err) {
if(err){
console.log(err);
}else{
console.log(req.body);
console.log('files', req.files);
}
})
res.status(200).send({});
});
// output
{ data: '{"test":"test"}' }
files [ { fieldname: 'file',
originalname: 'acfcdea5-28d2-4f2e-a897-1aef3507193d.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './uploads/',
filename: 'acfcdea5-28d2-4f2e-a897-1aef3507193d.jpg',
path: 'uploads\\acfcdea5-28d2-4f2e-a897-1aef3507193d.jpg',
size: 49647 } ]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6426 次 |
最近记录: |