Reputation: 1326
I have a file upload that is working properly, however, I would like to pass a JSON object that contains other details, such as who created the file, file display name, and file path to upload. Each file type will need to be uploaded in a certain location which I get from the database. Currently my file upload will upload all the files into one location. If this is not possible can I pass the upload path URL in the header only?
HTML
<input name="file" type="file" (change)="onChange($event)" style="width:80%" [disabled]='showDeleteButton' />
component
onChange(event: any) {
var files = event.srcElement.files;
this.file = files[0];
this.fileName = this.file.name;
console.log('file name ' + this.fileName);
this._uploadService.makeFileRequest(this.baseURL + 'UploadFiles', [], files).subscribe(() => {
console.log('file name ' + this.fileName);
});
service
makeFileRequest(url: string, params: string[], files: File[]): Observable<any> {
return Observable.create((observer: Observer<number>) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
WebAPI
[HttpPost]
[Route("API/FileUpload/UploadFiles")]
public HttpResponseMessage UploadFiles()
{
var file = HttpContext.Current.Request.Files[0];
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/upload/"), fileName);
// var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/upload/1/1/"), fileName);
file.SaveAs(path);
var content = JsonConvert.SerializeObject(fileName, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(content, Encoding.UTF8, "application/json");
return response;
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "faild");
}
I would like to pass this object
or if there is anyway to pass the upload path in the header instead?
Upvotes: 0
Views: 1705
Reputation: 1200
Add your JSON data into the form Data which you are building in service method, and access it in Web API.
formData.append("uploads[]", files[i], files[i].name);
formData.append("fileInfo" <your JsonData>);
WebAPI method that takes a file upload and additional arguments
Upvotes: 1