Sending files from angular 6 application to spring boot web api "Required request part 'file' is not present" - rest

I'm trying to send an file from angular 6 front-end to spring boot web API.
but it gives me following error
Bad Request","message":"Required request part 'file' is not present
here is my html code to upload file
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file" name="file" (change)="fileChange($event)" class="form-control-file" id="exampleInputFile" aria-describedby="fileHelp">
</div>
<button (click)="uploadFile()" type="button" class="btn btn-primary">Upload</button>
here is my ts code
formData:FormData = new FormData();
readytoupload:boolean=false;
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
this.formData.append('file', file);
this.readytoupload =true;
}
}
uploadFile(){
if(this.readytoupload){
this.featureservice.uploadFIle(this.formData).subscribe(data => {
const a = data.json();
this.goToProcess(a.process_id)
});
}
}
Here is the angular serivice
uploadFIle(formData:FormData){
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append("Content-Type", 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW');
return this.http.post(this.url+'upload',formData,{headers: headers})
};
this is the back-end controller
#CrossOrigin(origins = "*")
#PostMapping(value = "api/upload")
public String uploadReviews(#RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
return null;
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(uploadFolder + file.getOriginalFilename());
uploadFile = path.toString();
Files.write(path, bytes);
sessionID = "6";
} catch (IOException e) {
e.printStackTrace();
return null;
return sessionID;
}
above API service is perfectly working with Postman requests. But not working with angular requests.
Can any one please help me on this?

Instead of this :-
return this.http.post(this.url+'upload',formData,{headers: headers})
Use this :-
return this.http.post(this.url+'upload',{"file" : formData},{headers: headers})
Hope this helps

this worked for me
downloadPdf(file: File): Observable<HttpEvent<any>>{
const formData: FormData = new FormData();
formData.append('file', file);
const req = new HttpRequest('POST', `${this.url}/upload`, formData, {
reportProgress: true,
responseType: 'arraybuffer' as 'json'
});
return this.http.request(req);
}

Related

upload video file to server using ionic framework capacitor and web api for android and ios

I am trying to upload video file to the remote server using ionic framework capacitor and webApi. But when run the code, it is showing the error like Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'. Parameter name: content with ionic.
My Code: MyController.cs(webApi):
[Route("api/Upload")]
public async Task<string> Upload()
{
try
{
var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];
var provider = new MultipartFormDataStreamProvider(fileuploadPath);
var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
foreach (var header in Request.Content.Headers)
{
content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
await content.ReadAsMultipartAsync(provider);
string uploadingFileName = provider.FileData.Select(x => x.LocalFileName).FirstOrDefault();
string originalFileName = String.Concat(fileuploadPath, "\\" + (provider.Contents[0].Headers.ContentDisposition.FileName).Trim(new Char[] { '"' }));
if (File.Exists(originalFileName))
{
File.Delete(originalFileName);
}
File.Move(uploadingFileName, originalFileName);
return "success";
}
catch (Exception ex)
{
return ex.Message;
}
}
webconfig.cs:
<add key="FileUploadLocation" value="D:\Asp.Net\Fileupload" />
upload.html:
<input #fileInput type="file" [multiple]="true" (change)="uploadFiles( fileInput.files ); fileInput.value = null;"/>
upload.ts:
public async uploadFiles( files: File[] ) : Promise<void>
{
Array.from(files).forEach(async(file1:any)=>
{
try
{
this.uploads.push(await this.Service.uploadFile(file1));
}
catch ( error )
{
console.warn( "File upload failed." );
console.error( error );
}
});
}
service.ts:
public async uploadFile( file: File ) : Promise<UploadResult>
{
var result = await this.httpClient.post<ApiUploadResult>("http://12.99.45.21:8021/Mobile/api/Upload",file, // Send the File Blob as the POST body.
{
headers: {
"Content-Type": file.type
},
params: {
clientFilename: file.name,
mimeType: file.type
}
}
)
.toPromise();
return({
name: file.name,
type: file.type,
size: file.size,
url: result.url,
});
}
I got 200 ok status. But the video file is not saved on the specify path. But when I run the API on postman, it is working fine.
Please help to resolve this issue.

upload file to server using ionic framework and web api

I am trying to upload video file to the remote server using ionic framework capacitor and webApi. But when run the code, it is showing the error like Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'. Parameter name: content with ionic.
My Code:
MyController.cs(webApi):
[Route("api/Upload")]
public async Task<string> Upload()
{
try
{
var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];
var provider = new MultipartFormDataStreamProvider(fileuploadPath);
var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
foreach (var header in Request.Content.Headers)
{
content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
await content.ReadAsMultipartAsync(provider);
string uploadingFileName = provider.FileData.Select(x => x.LocalFileName).FirstOrDefault();
string originalFileName = String.Concat(fileuploadPath, "\\" + (provider.Contents[0].Headers.ContentDisposition.FileName).Trim(new Char[] { '"' }));
if (File.Exists(originalFileName))
{
File.Delete(originalFileName);
}
File.Move(uploadingFileName, originalFileName);
return "success";
}
catch (Exception ex)
{
return ex.Message;
}
}
webconfig.cs:
<add key="FileUploadLocation" value="D:\Asp.Net\Fileupload" />
upload.html:
<input #fileInput type="file" [multiple]="true" (change)="uploadFiles( fileInput.files ); fileInput.value = null;"/>
upload.ts:
public async uploadFiles( files: File[] ) : Promise<void>
{
Array.from(files).forEach(async(file1:any)=>
{
try
{
this.uploads.push(await this.Service.uploadFile(file1));
}
catch ( error )
{
console.warn( "File upload failed." );
console.error( error );
}
});
}
service.ts:
public async uploadFile( file: File ) : Promise<UploadResult>
{
var result = await this.httpClient.post<ApiUploadResult>("http://12.99.45.21:8021/Mobile/api/Upload",file, // Send the File Blob as the POST body.
{
headers: {
"Content-Type": file.type
},
params: {
clientFilename: file.name,
mimeType: file.type
}
}
)
.toPromise();
return({
name: file.name,
type: file.type,
size: file.size,
url: result.url,
});
}

how can i add Authorization : "JWT <token>" to http request ? in Nuxt.js

I am developing with Nuxtjs and using nuxtauth.
I am trying to give the content " JWT " to the Authorization of http request.
However, even if I change the string to be given by coding, "Bearer " is sent and I get a 401 error.
The formed text (including the JWT) can be seen in the console.
The process is as follows.
<template>
<div>
<button #click="getUserInfo">get user data</button>
<div>
{{ responseData }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
pretoken: this.$auth.strategy.token.get(),
responseData: {}
};
},
methods: {
async getUserInfo() {
const url = "/server/v1/mypages/";
const pretoken = this.pretoken;
const fixedtoken = pretoken.replace("Bearer", "JWT");
console.log(fixedtoken);
this.$axios.setHeader("Authorization", fixedtoken);
this.responseData = await this.$axios.get(url);
}
}
};
</script>
How can I achieve this?
try the codes below and it should work
const config = { headers: { 'Authorization': fixedtoken } };
this.responseData = await this.$axios.get(url, config);

Download zip file using Angular

It has been hours now, since I am trying to figure out how to download a zip file using Angular.
The file downloaded is smaller than the original file. I followed this link How do I download a file with Angular2.
I am not simply using the <a> tag for the download for authentication reason.
service
downloadfile(filePath: string){
return this.http
.get( URL_API_REST + 'downloadMaj?filePath='+ filePath)
.map(res => new Blob([res], {type: 'application/zip'}))
}
component
downloadfileComponent(filePath: string){
this.appService.downloadfile(filePath)
.subscribe(data => this.getZipFile(data)),
error => console.log("Error downloading the file."),
() => console.log('Completed file download.');
}
getZipFile(data: any){
var a: any = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var blob = new Blob([data], { type: 'application/zip' });
var url= window.URL.createObjectURL(blob);
a.href = url;
a.download = "test.zip";
a.click();
window.URL.revokeObjectURL(url);
}
rest api
public void downloadMaj(#RequestParam(value = "filePath") String filePath, HttpServletResponse response) {
System.out.println("downloadMaj");
File fichierZip = new File(filePath);
try {
System.out.println("nom du fichier:" + fichierZip.getName());
InputStream inputStream = new FileInputStream(fichierZip);
response.addHeader("Content-Disposition", "attachment; filename="+fichierZip.getName());
response.setHeader("Content-Type", "application/octet-stream");
org.apache.commons.io.IOUtils.copy(inputStream, response.getOutputStream());
response.getOutputStream().flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Anyone could tell why all the file is not downloaded?
Solved
downloadfile(filePath: string) {
return this.http
.get( URL_API_REST + 'download?filePath=' + filePath, {responseType: ResponseContentType.ArrayBuffer})
.map(res => res)
}
private getZipFile(data: any) {
const blob = new Blob([data['_body']], { type: 'application/zip' });
const a: any = document.createElement('a');
document.body.appendChild(a);
a.style = 'display: none';
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = test.zip;
a.click();
window.URL.revokeObjectURL(url);
}
In responseType you need to assign a string, in this case, is arraybuffer (Angular 5+)
downloadFile(filename: string) {
return this.http.get(URL_API_REST + 'download?filename=' + filename, {
responseType: 'arraybuffer'
});
}
We can do a window to download directly our file using next code:
this.myService.downloadFile(filename).subscribe(data => {
const blob = new Blob([data], {
type: 'application/zip'
});
const url = window.URL.createObjectURL(blob);
window.open(url);
});
There are multiple plugins you'll need to get zip download working using angular:
angular-file-saver.bundle
This plugin will bundle Blob.js and FileSaver.js
follow all instructions now just add dependencies on your controller and module.
.module('fileSaverExample', ['ngFileSaver'])
.controller('ExampleCtrl', ['FileSaver', 'Blob', ExampleCtrl]);
add JSZip and JSZipUtils
Include files:jszip.js, jszip-utils.js, angular-file-saver.bundle.js
var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");
// when everything has been downloaded, we can trigger the dl
zip.generateAsync({type:"blob"}).then(function (blob) { // 1) generate the zip file
FileSaver.saveAs(blob, "downloadables.zip"); // 2) trigger the download
}, function (err) {
console.log('err: '+ err);
});
In Angular there is no need of jsZip-util ,you can simple make an service call with header options.
public zipAndDownload(url): Observable<any> {
const options:any = {
headers: new HttpHeaders({'Content-Type': 'file type of an particular document'}),
withCredentials: true,
responseType:'arraybuffer'
};
return this.http.get<Content>(url,options);
}
I use FileSaver
to save files on my local machine. It accepts either blob or string data and saves the file with the given/default name. From the official document:
function FileSaver.saveAs(data: string | Blob, filename?: string, options?: FileSaver.FileSaverOptions): void
Download.Service.ts
downloadFile() {
return this.http.get(url, { params, responseType: 'arraybuffer', observe: 'response' }).pipe(
map(res => res)
);
}
my.component.ts
this.downloadService.downloadFile().subscribe((response: HttpResponse<any>) => {
if(response.body) {
let fileName = "download.zip";
const cDisposition: string = response.headers.get('content-disposition');
if (cDisposition && cDisposition.indexOf(';filename=') > -1) {
fileName = cDisposition.split(';filename=')[1];
}
const data = new Blob([new Uint8Array(response.body)], {
type: 'application/octet-stream'
});
FileSaver.saveAs(data, fileName);
}
})

Excel file reading in mvc5 using javascript function

The Excel sheet want to read while it upload on a button click in MVC5.The uploaded excel file name is passed into action using AJAX method.Here the file variable get null value in posted method.
Here how can pass selected file as HttpPostedFileBase in the below ajax method.
`
<input style="display:none" type="file" id="fileupload1" />
<button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
<span style="display:none" id="spnName"></span>
$(function () {$("#fileupload1").change(function () {
$("#spnName").html($("#fileupload1").val().substring($("#fileupload1").val().lastIndexOf('\\') + 1));
var file = $("#spnName").html();
$.ajax({
url: "UploadExcelForContractStaff",
type: 'POST',
data: JSON.stringify({ file: file }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
});
});`
[AcceptVerbs(HttpVerbs.Post)]
public string UploadExcelForContractStaff(HttpPostedFileBase uploadFile)
{
StringBuilder strValidations = new StringBuilder(string.Empty);
try
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
DataSet ds = new DataSet();
//A 32-bit provider which enables the use of
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";
using (OleDbConnection conn = new System.Data.OleDb.OleDbConnection(ConnectionString))
{
conn.Open();
using (DataTable dtExcelSchema = conn.GetSchema("Tables"))
{
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
string query = "SELECT * FROM [" + sheetName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
//DataSet ds = new DataSet();
adapter.Fill(ds, "Items");
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//Now we can insert this data to database...
}
}
}
}
}
}
}
catch (Exception ex) { }
return "";
}
I got solution. changed code like
<form enctype="multipart/form-data" id="frmUplaodFileAdd">
#Html.AntiForgeryToken()
<input style="display:none" type="file" id="fileupload1" />
<button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
<span style="display:none" id="spnName"></span>
</form>
$.ajax({
url: "UploadFile", //Server script to process data
type: 'POST',
async: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) { }
});
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{return Json();
}