I am working on an API which will accept the file and other details as input object like below
attachmentDto:{
Attachment_Description:"Description",
ApplicationId:1212,
etc...
}
So I created a method like
[HttpPost]
public IHttpActionResult SaveAttachment(AttachmentDto attachmentDto)
{
var file = HttpContext.Current.Request.Files[0];
process();
return Ok();
}
Does anybody gone through such situation.
Please provide the solutions or alternatives as well.
Thanks in advance.
Answer is like below:
attachmentDto:{
Attachment_Description:"Description",
ApplicationId:1212,
Prop1: prop1value,
prop2: prop2value
}
$.customAjax({
type: "POST",
url: url,
data:attachmentDto,
success: function (returnData) {
//success
},
error:function()
{
//error
}
});
Hope this helps you.
Related
I would like to build a node application using REST, need to read data from readymade api and store it in class for temp, and then save it to MySQL. Can anyone have any idea about this?
This is a very simple job.
Let's consider Typescript, but you can achieve the same result with JavaScript. I'll be using node-fetch as an example of the rest API library. Do note that the code might not be syntactically correct.
First: Create interfaces/classes that reflect the data you will receive from the REST API
interface Food {
id: number,
name: string,
...
}
Second:
Create a Repository
Create a class Repository which you will use to communicate with the rest API
class Repository {
async function getFoods(...args): List<Food> {
let foods = await fetch({url: "url"});
return foods;
}
async function addFood(food: Food): Response {
let response = await fetch({
url: "url-to-add-food",
method: "post",
data: JSON.stringify(food)
});
}
}
Third:
Use the repository to fetch the data and use conventional methods to save it to a MySQL database
let foods = await repository.getFoods();
foods.forEach(food => {
connection.query('INSERT INTO foods SET ?', food,
function (err, resp) {
if (err) throw err;
}
);
});
I would like to display the name of the person who logged in the app. I tried this
getprotected() {
return this.http.get(${this.url}/api/protected_things)
.pipe(
catchError(e => {
let status = e.status;
if (status === 401) {
this.showAlert('You are not authorized for this!');
this.logout();
}
throw new Error(e);
})
)
}
tab1.ts
export class Tab1Page implements OnInit {
data = '';
constructor(private authService: AuthService, private storage: Storage, private toastController: ToastController, private http: HttpClient) { }
ngOnInit() {
this.authService.getprotected().subscribe(res => {
this.data = res['name'];
});
}
tab1.html
<p class="ion-text-center">Bienvenu</p>
<p class="ion-text-center"><b>{{ data }}</b></p>
<ion-button expand="full" (click)="logout()">Deconnecte Toi</ion-button>
but ts not working.
thank you
you should try to access the data you need with res.name.
As a general rule of thumb, try logging your result.
A simple console.log(res) from within the .subscribe() will help you visualize the object you receive.
If the problem happens early, the chrome network inspector will help you detect the data you receive. Keep in mind that an empty object will not trigger your catch error. To know more about network tab in chrome: https://www.youtube.com/watch?v=e1gAyQuIFQo&
By the way you should watch some tutorial, on youutbe you can find great material
I am trying to return a file from GridFS using my Nest controller. As far as I can tell nest is not respecting my custom content-type header which i set to application/zip, as I am receiving a text content type upon return (see screenshot).
response data image, wrong content-type header
My nest controller looks like this
#Get(':owner/:name/v/:version/download')
#Header('Content-Type', 'application/zip')
async downloadByVersion(#Param('owner') owner: string, #Param('name') name: string, #Param('version') version: string, #Res() res): Promise<any> {
let bundleData = await this.service.getSwimbundleByVersion(owner, name, version);
let downloadFile = await this.service.downloadSwimbundle(bundleData['meta']['fileData']['_id']);
return res.pipe(downloadFile);
}
Here is the service call
downloadSwimbundle(fileId: string): Promise<GridFSBucketReadStream> {
return this.repository.getFile(fileId)
}
which is essentially a pass-through to this.
async getFile(fileId: string): Promise<GridFSBucketReadStream> {
const db = await this.dbSource.db;
const bucket = new GridFSBucket(db, { bucketName: this.collectionName });
const downloadStream = bucket.openDownloadStream(new ObjectID(fileId));
return new Promise<GridFSBucketReadStream>(resolve => {
resolve(downloadStream)
});
}
My end goal is to call the download endpoint and have a browser register that it is a zip file and download it instead of seeing the binary in the browser. Any guidance on what needs to be done to get there would be greatly appreciated. Thanks for reading
You also need to set the Content-Disposition header with a file name. You can use the #Header() decorator if the file name will always be the same or setHeader directly on the response object if you need to be able to send back different file names based on some parameter in your controller.
Both of the following example controller methods work for sending back a downloadable file to the browser from my local file system.
#Get('/test')
#Header('Content-Type', 'application/pdf')
#Header('Content-Disposition', 'attachment; filename=something.pdf')
getTest(#Res() response: Response) {
const data = createReadStream(path.join(__dirname, 'test.pdf'));
data.pipe(response);
}
#Get('/test')
#Header('Content-Type', 'application/pdf')
getTest(#Res() response: Response) {
const data = createReadStream(path.join(__dirname, 'test.pdf'));
response.setHeader(
'Content-Disposition',
'attachment; filename=another.pdf',
);
data.pipe(response);
}
I have a generic SendMail route which I want to create multiple remote methods to handle multiple request templates. Any ideas on how to return a Email_Type from the remote method back to the base route. I know I could add a default with a code in it, but would like a more elegant solution.
Mail.genericSendMail = function genericEmail(response, callback) {
console.log(response);
let templateId=0;
//PROBLEM: HOW TO KNOW WHICH REMOTE WAS USED
switch (response.emailType) {
case "Template-1":
templateId= 1234;
break;
case "Template-2":
tempalteId = 456;
break;
default:
templateId = 789l
} //switch
console.log(templateId);
};
//Want multiple routes like this to support various templates
Mail.remoteMethod("genericEmail", {
http: {
path: "/emailTemplate1",
verb: "POST"
},
accepts [
{arg: "request", type:"object",http: {source:"body"},
default: {firstName:"", lastName:"",emailAddress:""}
}],
returns: RESTResponseStatic.loopbackAdapterCommonRestResponseDefinition()
});
//Want multiple routes like this to support various templates
Mail.remoteMethod("genericEmail", {
http: {
path: "/emailTemplate2",
verb: "POST"
},
accepts [
{arg: "request", type:"object",http: {source:"body"},
default: {emailAddress:"", promoCode:""}
}],
returns: RESTResponseStatic.loopbackAdapterCommonRestResponseDefinition()
});
There are a couple of different ways to do this. Since it happens to be a POST request, I usually go with attaching data to the body using a before remote hook.
Let's say you have a model method for logging in users.
Say we have a multi realm platform, so we need to know what platform we are logging in. If you don't use realms or don't know what they are, don't worry. This just shows you how to populate the data to the model method.
User.login = function(data, cb) {
if (data.realm == 'platform1) {
return logUserIntoPlatform1(data, cb);
}
return logUserIntoDefaultPlatform(data, cb);
}
Now let's say you don't want the client/frontend to send the realm and you don't want to do the lookup for realm in the model. We can add a beforeRemote hook like so:
User.beforeRemote('login', function (context, user, next) {
context.args.data.realm = lookUpRealmSync(context); // 1
next();
});
This will be called before the login method. Note the next() call: this is how you could do error detection before actually hitting the model method. Something like next({ status: 422, message: 'Parameter missing: password }); would return an error and not execute the User.login method.
You may have to look carefully at your context object (i.e. the line marked with 1 may not work exactly as I've shown for you).
If you want to read more about this stuff, I LoopBack's docs are pretty good. It seems they've been updated since I've last used them so I can't link you to the more useful pages. I found the remote method documentation here though.
Edit: I took a closer look at your question. You should be able to retrieve the path from the context object and pass data accordingly. I'm not going to try to code that since I don't know where it would actually be within the object.
I'm new to sparkjava. I want to read my request params using spark java but I'm not able to find the correct syntax. please help me out. Below is my route method and the client call to it:
my client request url:
/smartapp/getDataViewModelConfig?collId=123'
Route Method:
get("smartapp/getDataViewModelConfig/:id", "application/json", (request, response)
-> {
String id = request.params(":id");
}
The 'id' field is returning null here. Any suggestions as to what went wrong here?
If you have to work with an URL like /smartapp/getDataViewModelConfig?collId=123 you have to deal with query parameters in your implementation, like the following:
get("smartapp/getDataViewModelConfig", "application/json", (request, response)->{
String id = request.queryParams("collId");
return "HI " + id;
}
If you have an URL like : http://localhost:4567/smartapp/getDataViewModelConfig/456
use the following code :
get("/smartapp/getDataViewModelConfig/:id","application/json", ((request, response) -> {
response.type("application/json")
return request.params(":id");
}), gson::toJson);