I am new in Angular, and trying to upload file from front-end to the server but I get failed in that.
post the file using Postman is working successfully, but when I apply on the browser I got the error below in the image:
my code as the following:
.service.ts file (The service function is)
upload_document(ProductID: any, document_data: any, file_data: any):Observable<any> {
return this.httpClient.post(`${API_SERVER_URL}/api/products/upload_document/${ProductID}`, {document_data: document_data, file_data:file_data}).pipe(
tap(async (res: any)=>{
console.log(res);
})
)
}
.component.ts (uploadFile + clickUpload) functions
uploadFile(event: Event) {
const element = event.currentTarget as HTMLInputElement;
let fileList: FileList | null = element.files;
if (fileList) {
console.log("FileUpload -> files", fileList);
}
}
clickUpload() {
this.productService.upload_document(this.ProductID, this.frmGroup.value, this.file_data).subscribe(
result=>{
this.frmGroup.get('FileName')?.setValue('');
this.frmGroup.get('CategoryID')?.setValue('');
this.frmGroup.get('Remarks')?.setValue('');
this.frmGroup.get('Path')?.setValue('');
this.frmGroup.get('UploadedBy')?.setValue('');
alert("Document Uploaded");
},
error => {
alert("Please Try Again");
})
}
.component.html
<form #formSubmit="ngForm" class="col-md-offset-3 col-md-6" [formGroup]="frmGroup" (ngSubmit)="clickUpload()">
<input type="file" name="Path" formControlName="Path" accept="image/png, image/jpeg, application/pdf" (change)="uploadFile($event)">
<label>File Name</label>
<input type="text" name="FileName" formControlName="FileName">
<button type="submit" class="bg-primary">Upload</button>
</form>```
I need a help to upload the file to backend server (API call)
Related
I'm trying to set up a really simple page to render documents based on inputs. I have a form with some inputs on one page, and I want the data appear on the next page when submitted.
I'm still learning Next and I'm trying to use the pages/api to do this but I am not sure how exactly it works.
As of now when I submit the form it is redirecting me to a JSON page with the data, how can I make is so when I hit submit, it uses the JSON data to redirect to another page displaying it?
Here is the code:
index.js
export default function Home() {
return (
<>
<h1 Name Generator</h1>
<form action="/api/form" method="post">
<div>
<label for="name">Name</label>{" "}
<input
type="text"
id="name"
name="name"
placeholder="Enter name."
required
/>
</div>
<div>
<button style={{ display: "flex" }} type="submit">
Submit
</button>
</div>
</form>
</>
);
}
pages/api/form.js
export default function handler(req, res) {
// Get data submitted in request's body.
const body = req.body;
// Optional logging to see the responses
// in the command line where next.js app is running.
console.log("body: ", body);
// Guard clause checks for name,
// and returns early if they are not found
if (!body.subject || !body.teachers) {
// Sends a HTTP bad request error code
return res.status(400).json({ data: "name not found" });
}
// Found the name.
// Sends a HTTP success code
res.status(200).json({
data: {
name: `${body.name}`,
},
});
}
here is the result page I want it to render the data into and what I tried
result.js
import { data } from "../pages/api/form";
export default function Result() {
console.log(data);
return (
<>
<>
<h1>Name Generator</h1>
<hr></hr>
<div>
<h4>Name</h4>
<hr></hr>
{data.name}
</div>
</>
))
</>
);
}
When I submit I get JSON at
host/api/form
data: {
name: "name"
}
I am not sure what to try as I believe there is a simple way to do this that I am just missing
I have an extension in MS Teams, which open a task module - basically an angular application. as seen below:
The functionality of the app is to perform upload images.
HTML Code:
<input type="file" class="file-input" (change)="onFileSelected($event)" #fileUpload />
So, the issue is when I click the button on ios it gives me the option to upload from camera. But that’s not the case in android
After doing some research I tried a couple of options in HTML
<input accept="image/*" capture type="file" class="file-input" (change)="onFileSelected($event)" #cameraUpload />
or,
<input type="file" accept="image/*;capture=camera">
none of them works inside the teams.
Now when I run the app in the browser and click on file upload it shows the camera options:
How can I perform the same functionality inside MS Teams, task module
You can add below permissions to your manifest to support media capabilities:
"devicePermissions": [
"media"]
let imageProp: microsoftTeams.media.ImageProps = {
sources: [microsoftTeams.media.Source.Camera, microsoftTeams.media.Source.Gallery],
startMode: microsoftTeams.media.CameraStartMode.Photo,
ink: false,
cameraSwitcher: false,
textSticker: false,
enableFilter: true,
};
let mediaInput: microsoftTeams.media.MediaInputs = {
mediaType: microsoftTeams.media.MediaType.Image,
maxMediaCount: 10,
imageProps: imageProp
};
microsoftTeams.media.selectMedia(mediaInput, (error: microsoftTeams.SdkError, attachments: microsoftTeams.media.Media[]) => {
if (error) {
if (error.message) {
alert(" ErrorCode: " + error.errorCode + error.message);
} else {
alert(" ErrorCode: " + error.errorCode);
}
}
if (attachments) {
let y = attachments[0];
img.src = ("data:" + y.mimeType + ";base64," + y.preview); }
});
Can you please refer below documentation to integrate media capabilities.
https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/device-capabilities/mobile-camera-image-permissions
Git Repo for sample code:
https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/tab-device-permissions/nodejs
I am trying to upload files to the server. I created an Express-App with an index.html and an index.js file.
The index.html file:
<h1>File Upload in Node.js App</h1>
<form method="POST" action="/" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
The index.js file:
app.post('/', (req,res)=>{
console.log("post file")
if(req.files){
console.log(req.files);
var file = req.files.file
var filename = file.name;
console.log(filename);
file.mv('./uploads/' + filename, function(err){
if(err){
res.send(err)
} else {
res.send("File Uploaded")
}
})
}
})
It worked very well.
I am trying the post method now within my Angular-App
app.component.html
<h1>File Upload in Node.js App</h1>
<input type="file" (change)="fileChange($event)" name="file">
<button (click)="uploadFiles()">Upload</button>
app.component.ts:
fileChange(element) {
this.files_to_upload = element.target.files;
console.log(this.files_to_upload);
}
uploadFiles(){
const body = {
files: this.files_to_upload
}
console.log(body);
this.http.post("http://localhost:3000/",body)
.subscribe(res => console.log(res));
The body is different when using the form but why?
In my Express-App req.files is not initialized because the function is just console logging Post file and stops there.
What is the difference between the two approaches (their bodies) and why does my approach in my Angular-App not work?
What would I have to change? I do not get it.
I'm doing a CRUD with vue-cli and nodejs on the server side. So I have a form like this
<template>
<div id="formRoot">
<div class="form" >
<form #submit.prevent="sendToTable" action="/create" method="post">
Name
<input type="text" v-model="row.name" name="name" />
Price
<input type="number" name="price" v-model="row.price" />
Description
<textarea v-model="row.description" rows="3" name="desc"/>
<input type="submit" id="button" value="SAVE" />
</form>
</div>
<form class="" action="create" method="post">
<input type="text" name="input">
<input type="submit" value="send">
</form>
</div>
</template>
<script>
export default{
data(){
return{
row: {
name: '',
price: '',
description: ''
}
}
},
methods: {
sendToTable() {
console.log(this.row);
this.$parent.addToTable(this.row);
}
}
}
</script>
the #submit.prevent is for avoid the page refreshing and of course I have a method named sendToTable.
in node I have this:
const path = require('path');
const morgan = require('morgan');
const app = express();
//middlewares
app.use(express.urlencoded({extended: false}));
app.use(express.static(path.resolve(__dirname, '../dist')));
app.use(morgan());
app.post('/create', (req, res) => {
console.log(req.body);
});
const port = 3000;
app.listen(port, () => {
console.log('server listening on port ' + port);
});
the problem is that the server cant get the post request, I think is because the #prevent.default property.
I tried sending a post request with postman and it works, so I'm sure the problem is in the frontend.
What should i do? How are actually coded those single page web apps that can send data to the server?
You need to actually post your form data via an HTTP request. You can use a library like Axios (very popular) or fetch (check the supported browsers list).
Another thing you appear to be doing is calling a method on this component's parent. That goes against Vue's one-way data flow and isn't optimal. The better solution is to have your component emit an event with the attached data.
For example (using fetch)
<form #submit.prevent="sendToTable" method="post" action="/create">
methods: {
async sendToTable ($event) {
const form = $event.target
// post form as a regular "submit" would
let res = await fetch(form.action, {
method: form.method,
body: new URLSearchParams(new FormData(form))
})
if (res.ok) {
// emit the "row-added" event to the parent
this.$emit('row-added', { ...this.row }) // using spread syntax to break references
} else {
// you might want to do something else here in case of an error
console.error(res)
}
}
}
and in your parent component (assuming the child component is named RowAdder)
<RowAdder #row-added="addToTable"/>
EDIT: Edited it using Mikhail's suggestion. Got closer to the solution
Hi I am trying to upload a JSON file using nodejs but for some reason it says my file is undefined. A file appears in my Public folder that contains the contents of the uploaded file however. I was wondering if someone would be able to help me out. Thanks
Here is the HTML
<form method="post" enctype="multipart/form-data" action="/file-upload">
<input type="file" name="theFile" >
<input type="submit" class = "submit">
</form>
EDIT: Here is the server.js
app.post('/testtwilio',upload.single('theFile'),function(req, res, next) {
console.log('FIRST TEST: ' + req.file);
});
Here is the JSON file
[{"name":"FIRST LAST","date":"12/22/2016","number":"7523924324"}]
Here is what is being logged
FIRST TEST: [object Object]
Change your JSON.stringify(req.files) to JSON.stringify(req.file)
Full code
HTML
<form id = "uploadForm" enctype = "multipart/form-data" action = "/api/file" method = "post">
<input type="file" name="userFile" />
<input type="submit" value="Upload File" name="submit">
</form>
JS
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
app.post('/api/file', upload.single('userFile'), function (req, res, next) {
console.log(JSON.stringify(req.file))
})
app.listen(3000,function(){
console.log("Working on port 3000");
});
Note:
File name which you use in multer.single() method should match name in input <input type="file" name="userFile" />
If you use the .single(...) method the file will be in req.file.