File upload is not working in aurelia js - content-type

I need to upload files in Aurelia Js. I don't know how to send file to server(hit to given API). I have two doubts, one is in my 'content-type' and another one is, do i need to change my image object to any other format. Here is the code i used,
scanupload.html :
<input type="file" files.bind="selectedFiles" change.delegate="onSelectFile($event)">
scanupload.js :
onSelectFile($event){ var myurl = 'http://cdn.dmiapp.tk/file?authToken=bLNYMtfbHntfloXBuGlSzPueilaHtZx&type=jpg&name=testfile.jpg&organizationId=1&userId=7&sourceType=USER_UPLOADS';
this.httpValueConverter.call_http(myurl,'POST',{file :this.selectedFiles[0]},'fileupload')
.then(data => {
console.log(data);
if(data.meta && data.meta.statusCode == 200) {
console.log('success');
}
});}
httpservice.js :
call_http(url,method,myPostData,action,params) {
return this.httpClient.fetch(url,
{
method: method,
body : myPostData,
headers : {
'authorization': this.authorization,
'Content-Type':'form-data'
}
})
.then(response => response.json());}
Error : bad request and unsupported media file.
Also tried content type, form-data and multipart/form-data

If it's an image your media type must be: "image/jpeg" and you can try to upload the image as a blob.
This does not seem to be an Aurelia-specific issue.
Try first to make a simple example working such as:
Upload image using javascript
When this works refactor it to an Aurelia view.
Also, verify that you have indeed configured your server to support the necessary mime type.
For multipart/form-data you can look at the following tweaks and packages:
https://github.com/expressjs/node-multiparty
https://github.com/expressjs/multer

Related

Sending multipart/form-data using GraphQL API in .NetCore

I'm trying to upload the user avatar of .png/jpeg/.jpg file types from angular client to .netCore server application using GraphQL API.
I managed to send the image to be uploaded in a request of content type multipart/form-data from client-side.
But getting a 400 Error from the API server saying the content-type is not supported.
Error message is as follows:
message: "Invalid 'Content-Type' header: non-supported media type.
Must be of 'application/json', 'application/graphql' or 'application/x-www-form-urlencoded'. See: http://graphql.org/learn/serving-over-http/."
I'm trying to implement the mutation like this.
FieldAsync<StringGraphType>(
"testImageUpload",
arguments: new QueryArguments(
new QueryArgument<StringGraphType> { Name = "testArg" },
new QueryArgument<UploadGraphType> { Name = "file" }
),
resolve: async context =>
{
var testArg = context.GetArgument<string>("testArg");
var file = context.GetArgument<IFormFile>("file");
try
{
return await uploaderService().UploadImage(file);
}
catch (Exception e)
{
context.Errors.Add(new ExecutionError("Something happened!"));
return context.Errors;
}
});
I'm using GraphQL.net and GraphQL.Upload.AspNetCore for supporting multipart files.
Sample mutation will be like this:
mutation testImageUpload($testArg: String, $file: Upload) {
fileUpload{
testImageUpload(testArg: $testArg, file: $file)
}
}
Can anybody suggest to me how to make the .NetCore webAPI application accept multipart/form-data.
Any help will be appreciated. Thanks in advance.
I, too, ran into this issue. The answer lies within your Startup.cs file.
First, the reason for which the "Invalid 'Content-Type' header" appears even while using GraphQL.Upload is because (at the time of this answer) the GraphQL.net middleware only checks for the three different Content-Type headers and errors out if none of those match. See GitHub
As for the solution, you haven't shared any of your Startup.cs file so I'm not sure what yours looks like. I'll share the relevant pieces of mine.
You'll need to add the service and the middleware.
The service:
services.AddGraphQLUpload()
.AddGraphQL((options, provider) =>
{
...
});
If you're using a endpoints to map to a middleware, you'll need to add the UseGraphQLUpload middleware, then map your endpoint.
Example:
app.UseGraphQLUpload<YourSchema>("/api/graphql", new
GraphQLUploadOptions {
UserContextFactory = (ctx) => new GraphQlUserContext(ctx.User)
});
app.UseEndpoints(endpoints =>
{
// map HTTP middleware for YourSchema at path api/graphql
endpoints
.MapGraphQL<YourSchema, GraphQLMiddleware<YourSchema>>("api/graphql")
.RequireAuthorization();
...
// Additional endpoints
...
}
Everything else looks fine to me.

Sending attachment file via http post request

I'm trying to send attachment file from youtrack to another system (in this example to trello) without the use of image url but its content
I cannot send it as image url in youtrack because my system is closed and accessible to only those that have vpn.
Problem is with reading inputStream from content of attachement in workflow. I symply have no idea how to do it and youtrack documentation havent touched it (as far as my research goes)
Code: (with truncated not important parts)
//...
exports.rule = entities.Issue.onChange({
//...
action: function(ctx) {
//...
var link = '/1/cards/' + issue['trelloIssueId'] + '/attachments';
issue.comments.added.forEach(function(comment) {
comment.attachments.forEach(function(attachment) {
var response = connection.postSync(link, {
name: attachment.name,
file: attachment.content,
mimeType: attachment.mimeType
});
//...
});
});
},
requirements: {}
});
from this I got error:
TypeError: invokeMember (forEach) on jetbrains.youtrack.workflow.sandbox.InputStreamWrapper#677a561f failed due to: Unknown identifier: forEach
How do I have to prepare content to ba abble to send it with postSync method?
It looks like you tried to iterate over issue.comments.added while the loop should be executed over issue.comments as there is no added key for an issue's comments Set as per the following documentation page suggest: https://www.jetbrains.com/help/youtrack/devportal/v1-Issue.html
Please let me know if that works.

Cypress: How to access the body of a POST-request?

Is there a way in Cypress to check the body of a POST-request?
E.g.: I have entered some data in a form, then pressed "Submit".
The form-data is send via POST-request, separated by a blank line from the header-data.
I would like to check the form-data. If all data, which I have entered, are included and if they are correct.
Is that possible with Cypress?
cy.get('#login').then(function (xhr) {
const body = xhr.requestBody;
console.log(xhr);
expect(xhr.method).to.eq('POST');
});
The xhr-object doesn't have the transferred data included.
It should be possible.
describe('Capturing data sent by the form via POST method', () => {
before(() => {
Cypress.config('baseUrl', 'https://www.reddit.com');
cy.server();
cy.route({
method: 'POST',
url: '/login'
}).as('redditLogin');
});
it('should capture the login and password', () => {
cy.visit('/login');
cy.get('#loginUsername').type('username');
cy.get('#loginPassword').type('password');
cy.get('button[type="submit"]').click();
cy.wait('#redditLogin').then(xhr => {
cy.log(xhr.responseBody);
cy.log(xhr.requestBody);
expect(xhr.method).to.eq('POST');
})
});
});
This is how you can inspect your data in Chrome Developer Tool.
You should see the same thing you've seen from Chrome Developer Tool when you run your test in Cypress.
I was Googling the same problem and somehow landed here before reaching the documentation.
Anyway, have you tried something like:
cy.wait('#login').should((xhr) => {
const body = xhr.request.body
expect(body).to.match(/email/)
})
I haven't tested it out with a multipart/form-data encoded request, but I suspect that you'll also find the request body that way.
Good luck!
It's better to use cy.intercept() in order to spy, stub and assert network requests and responses.
// assert that a request to this route
// was made with a body that included 'user'
cy.wait('#someRoute').its('request.body').should('include', 'user')
// assert that a request to this route
// received a response with HTTP status 500
cy.wait('#someRoute').its('response.statusCode').should('eq', 500)
// assert that a request to this route
// received a response body that includes 'id'
cy.wait('#someRoute').its('response.body').should('include', 'id')
Link to the docs

Alamofire v4, Swift v3 Uploading Sqlite file to domain

I’m trying to upload an Sqlite database from IOS Swift 3 to my server using Alamofire 4.0, but having problems converting the sqlite file into the data type required to upload.
The majority of posts / question examples seem to default to uploading images, but I am struggling to find example of uploading sqlite or other file types (for back-up purposes)
I have searched for the basic code and found this so far which looks very reasonable (thanks to following post: Alamofire 4 upload with parameters)
let parameters = ["file_name": "swift_file.jpeg"]
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(UIImageJPEGRepresentation(self.photoImageView.image!, 1)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to:"http://sample.com/upload_img.php")
{ (result) in
switch result
{
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
//Print progress
})
upload.responseJSON { response in
//print response.result
}
case .failure(let encodingError):
//print encodingError.description
}
}
The part I’m struggling with is to append the sqlite file to the upload (multipartFormData.append(………..?) I’ve searched but not found any good reference posts.
Yes, i’m a newbe, but trying hard, any help would be appreciated…..
It's exactly the same as the image example except that the mime type would be application/octet-stream.
Also, you'd probably go ahead and load it directly from the fileURL rather than loading it into a Data first.
As an aside, the parameters in that example don't quite make sense, as it looks redundant with the filename provided in the upload of the image itself. So you'd use whatever parameters your web service requires, if any. If you have no additional parameters, you'd simply omit the for (key, value) { ... } loop entirely.
Finally, obviously replace the file field name with whatever field name your web service is looking for.
// any additional parameters that must be included in the request (if any)
let parameters = ["somekey": "somevalue"]
// database to be uploaded; I'm assuming it's in Documents, but perhaps you have it elsewhere, so build the URL appropriately for where the file is
let filename = "test.sqlite"
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent(filename)
// now initiate request
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(fileURL, withName: "file", fileName: filename, mimeType: "application/octet-stream")
for (key, value) in parameters {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
}, to: urlString) { result in
switch result {
case .success(let upload, _, _):
upload
.authenticate(user: self.user, password: self.password) // only needed if you're doing server authentication
.uploadProgress { progress in
print(progress.fractionCompleted)
}
.responseJSON { response in
print("\(response.result.value)")
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
}
}
Unrelated, but if you're ever unsure as to what mime type to use, you can use this routine, which will try to determine mime type from the file extension.
/// Determine mime type on the basis of extension of a file.
///
/// This requires MobileCoreServices framework.
///
/// - parameter url: The file `URL` of the local file for which we are going to determine the mime type.
///
/// - returns: Returns the mime type if successful. Returns application/octet-stream if unable to determine mime type.
func mimeType(for url: URL) -> String {
let pathExtension = url.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream";
}

Node.JS Multipart upload to facebook graph

I'm trying to upload a photo to facebook and I can't find seem to get the multipart upload working. I can't find any documentation or libraries that do this. Has anyone else had any luck with this?
Check out the restler library for this instead. I've used it for this exact purpose, and it works great.
Here is some modified code from their examples to show how a file POST would go.
// multipart request sending a file and using https
rest.post('https://twaud.io/api/v1/upload.json', {
multipart: true,
data: {
'sound[message]': 'hello from restler!',
'sound[file]': rest.file('doug-e-fresh_the-show.mp3', null, null, null, 'audio/mpeg')
}
}).on('complete', function(data) {
sys.puts(data.audio_url);
});

Resources