Trouble with file upload using javascript swagger client and react - javascript

I have a problem with the source code generated by the Swagger codegen.
I want to upload a file with react. For this I have created a Dropzone and get a path to the file. If I use the generated client as it is in the documentation, it will not work. Unfortunately, the file is not sent. Only the file name. The debug console also does not show that binary data has been sent.
The request is not executed correctly. The file will not be uploaded. The parameter "file" is just the file name, instead of the binary data.
Swagger-codegen version
openapi-generator-cli-3.3.4.jar
Swagger declaration file content
Swagger .yaml:
/orders/upload:
post:
operationId: "orderUploadPart"
summary: "upload a textual or audio part of an order"
tags:
- "orders"
description: "This funktion uploads a textual or audio part of an order to the sense.ai.tion cloud system.
The result is the resource identifier, that must be used in the order request."
consumes:
- multipart/form-data
parameters:
- in: "formData"
name: "file"
type: "file"
required: true
description: "the file to upload"
- in: "formData"
name: "media"
type: "string"
enum:
- "text"
- "wav"
- "mp3"
required: true
description: "the media type of the the upload, can be ***text***, ***wav*** or ***mp3***"
Code:
var apiInstance = new SenseaitionApi.OrdersApi();
var file = "/path/to/file"; // File | the file to upload
var media = "media_example"; // String | the media type of the the upload, can be ***text***, ***wav*** or ***mp3***
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.orderUploadPart(file, media, callback);
It's like in: https://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/javascript/docs/PetApi.md#uploadFile
Screenshot Chrome DevTools
Command line used for generation
java -jar ${GOPATH}/bin/openapi-generator-cli.jar generate -i service_js_api.yaml -g javascript -o clients/javascript/senseaition-api-js -Dio.swagger.parser.util.RemoteUrl.trustAll=true

I found the mistake. The documentation of generated Javascript code is wrong. For uploading a file (Javascript object) must be passed, not the Path.
This line is wrong:
var file = "/path/to/file"; // File | the file to upload

Related

React Native get real path of file on Android

I'm using react-native-document-picker to select a file and react-native-fs to upload the file.
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.allFiles],
copyToCacheDirectory: false
});
I'm getting the uri as - content://com.android.providers.media.documents/document/image%3A24
Then I'm converting this to actual path using react-native-get-real-path.
RNGRP.getRealPathFromURI(res[0].uri)
.then(filePath =>{
realFilePath = filePath
console.log("real-path-->"+filePath)
ToastAndroid.show(filePath, ToastAndroid.SHORT);
})
The above method gives the path as /storage/emulated/0/Download/output-onlinepngtools.png but this working for few files, for others I'm getting null as the real-path.
This is the error I see while uploading the file - [Error: Socket is closed]

Google Drive API : ENOENT - but my file is just in the same directory

ENOENT - but my file is just in the same directory ...
Hi all I try to sent a file, birds.mp3, to my Google Drive using API. The file got to be reached by a function to be sent.
Despite that the file I try to send is just in the same folder that the code concerned, my console return me :
events.js:183
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open './birds.mp3'
Here my tree :
-- folder
|-- birds.mp3
|-- quickstart.js
Here my quickstart.js
module.exports.insertDrive = function (req) {
console.log("callback reached.")
var url = req.body.url;
var folderId = 'id';
var fileMetadata = {
'name': req.body.word,
parents: "id"
};
var media = {
mimeType: 'audio/*',
body: fs.createReadStream("./birds.mp3") // PATH FUNCTION HERE
};
drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
}, function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
console.log('File Id: ', file.id);
}
})};
I can't figure out why my file can't be reached. I have try several tricks like path.resolve and all, I have try to push my birds.mp3 in several folder if any, but that have failed.
Thanks.
If you're trying to load a file from the same directory as the current module and pass that to the Google API, then use __dirname instead of ./. The ./ uses the current working directory which will depend upon how the overall program was invoked and will not point at your module directory.
So, if the intended file is in the same directory as your module, then change this:
fs.createReadStream("./birds.mp3")
to this:
fs.createReadStream(path.join(__dirname, "birds.mp3"));

Bad XMLHttpRequest when uploading to S3

I'm using Evaporate.js to upload files to S3. I've had everything working, until I decided to enable server side encryption.
According to the S3 docs, you can enable it by passing a header. So I updated my add code to look like:
var promise = _e_.add({
name: name,
file: files[i],
started: callback_methods.started,
complete: callback_methods.complete,
cancelled: callback_methods.cancelled,
progress: callback_methods.progress,
error: callback_methods.error,
warn: callback_methods.warn,
paused: callback_methods.paused,
pausing: callback_methods.pausing,
resumed: callback_methods.resumed,
nameChanged: callback_methods.nameChanged,
xAmzHeadersAtInitiate: { 'x-amz-server-side​-encryption': 'AES256'} // THIS IS THE ONLY LINE THAT CHANGED!!!
}
)
I get the error: DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'AWS4-HMAC-SHA256 Credential=XXXXXXXXXXXXXXX/XXXXXXX/us-east-1/s3/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-server-side​-encryption, Signature=XXXXXXXXXXXXXXXXXXXXX' is not a valid HTTP header field value.
Update:
Header fields can only be ASCII characters. x-amz-server-side-encryption in your code contains a hidden character. Type it instead of copy pasting it from somewhere. Go to this web page and paste the header field name after copying from your question, you will see what i mean.
From the documentation:
You can't enforce whether or not objects are encrypted with SSE-S3 when they are uploaded using pre-signed URLs.
You need to sign the header along with the URL. Just sending the headers after signing the URL won't work.
var promise = _e_.add({
name: name,
file: files[i],
started: callback_methods.started,
complete: callback_methods.complete,
cancelled: callback_methods.cancelled,
progress: callback_methods.progress,
error: callback_methods.error,
warn: callback_methods.warn,
paused: callback_methods.paused,
pausing: callback_methods.pausing,
resumed: callback_methods.resumed,
nameChanged: callback_methods.nameChanged,
signHeaders: { 'x-amz-server-side-encryption': 'AES256' }, // notice this
xAmzHeadersAtInitiate: { 'x-amz-server-side-encryption': 'AES256'} // this should be fine now as we have the header in the signed request too but try removing this if you still get an error. S3 does not require you to re-specify the headers that were already signed.
});

How do I create a blank Google Spreadsheet using Drive API?

I created a web interface and I am trying to create a blank Google Spreadsheet with Drive API.
How do I create a blank Google Spreadsheet?
Try to use Drive API by setting the MIME Type to application/vnd.google-apps.spreadsheet
from apiclient import errors
from apiclient.http import MediaFileUpload
# ...
def insert_file(service, title, description, parent_id, mime_type, filename):
"""Insert new file.
Args:
service: Drive API service instance.
title: Title of the file to insert, including the extension.
description: Description of the file to insert.
parent_id: Parent folder's ID.
mime_type: MIME type of the file to insert.
filename: Filename of the file to insert.
Returns:
Inserted file metadata if successful, None otherwise.
"""
media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
body = {
'title': title,
'description': description,
'mimeType': mime_type
}
# Set the parent folder.
if parent_id:
body['parents'] = [{'id': parent_id}]
try:
file = service.files().insert(
body=body,
media_body=media_body).execute()
# Uncomment the following line to print the File ID
# print 'File ID: %s' % file['id']
return file
except errors.HttpError, error:
print 'An error occured: %s' % error
return None
Note: Apps creating shortcuts with files.insert must specify the MIME type application/vnd.google-apps.drive-sdk.

Node.js File to Angular file upload

I'm trying to figure out how to connect a Node.js FileSystem to an angular file upload directive.
I get the file from Node using:
var file = brackets.test.FileSystem.getFileForPath('/Users/me/Desktop/new-year-2015.jpg')
The resultant object looks like:
File {_isFile: true, _name: "new-year-2015.jpg", _parentPath: "/Users/me/Desktop/", _path: "/Users/me/Desktop/new-year-2015.jpg", _fileSystem: FileSystem…}_fileSystem: FileSystem_id: 89_impl: (...)_isFile: true_name: "new-year-2015.jpg"_parentPath: "/Users/me/Desktop/"_path: "/Users/me/Desktop/new-year-2015.jpg"
I'm trying to upload this object to server with:
$upload.upload({
url: 'https://localhost/upload',
file: file,
fileName: getFilenameFromPath(file),
});
On server the file is received as null.
How can I use a node.js file object in an angular file upload?

Categories

Resources