score:-3
you need to base64 encode the image and then send the body as a json (with the header content-type set to application/json)
score:0
you can use co-busboy
node module to write a middleware, this is an example for koa
:
firstly, you need to install co-busboy
by npm
or yarn
:
npm i co-busboy -s
or yarn add co-busboy
// upload.js
var parse = require('co-busboy')
var fs = require('fs')
var path = require('path')
var upload = function * (next) {
var parts = parse(this, {
autofields: true
})
while(var part = yield parts) {
part.pipe(fs.createreadstream(path.join('uploadpath', part.filename)))
}
yield next
}
module.exports = () => upload
// app.js
var upload = require('upload')
app.use(upload())
reference:
score:1
the example below uses react-native-fetch-blob at react native part, and nodejs with express and formidable to parse form at the server side.
let's first upload the file after determining whether user uploaded a photo or video:
rnfetchblob.fetch(
'post',
constants.upload_url + '/upload',
{
'content-type': 'multipart/form-data'
},
[
{
name: this.state.photourl ? 'image' : 'video',
filename: 'avatar-foo.png',
type: 'image/foo',
data: rnfetchblob.wrap(datapath)
},
// elements without property `filename` will be sent as plain text
{ name: 'email', data: this.props.email },
{ name: 'title', data: this.state.text }
]
)
// listen to upload progress event
.uploadprogress((written, total) => {
console.log('uploaded', written / total);
this.setstate({ uploadprogress: written / total });
})
// listen to download progress event
.progress((received, total) => {
console.log('progress', received / total);
})
.then(res => {
console.log(res.data); // we have the response of the server
this.props.navigation.goback();
})
.catch(err => {
console.log(err);
});
};
similarly, receive file and load the data accordingly:
exports.upload = (req, res) => {
var form = new formidable.incomingform();
let data = {
email: '',
title: '',
photourl: '',
videourl: '',
};
// specify that we want to allow the user to upload multiple files in a single request
form.multiples = true;
// store all uploads in the /uploads directory
form.uploaddir = path.join(__dirname, '../../uploads');
form.on('file', (field, file) => {
let suffix = field === 'image' ? '.png' : '.mp4';
let timestamp = new date().gettime().tostring();
fs.rename(file.path, path.join(form.uploaddir, timestamp + suffix)); //save file with timestamp.
data[field === 'image' ? 'photourl' : 'videourl'] = timestamp + suffix;
});
form.on('field', (name, value) => {
data[name] = value;
});
form.on('error', err => {
console.log('an error has occured: \n ' + err);
});
form.on('end', () => {
// now we have a data object with fields updated.
});
form.parse(req);
};
and use the controller function:
let route = express.router();
// other controller functions...
route.post('/upload', uploadcontroller.upload);
app.use(route);
make sure you read the comments included in the code. datapath is media's path (not base64 string) created after using react-native-image-picker . you can use react-native-progress to show upload progress.
check out multipartform-data section of react-native-fetch-blob for further reference: https://github.com/wkh237/react-native-fetch-blob#multipartform-data-example-post-form-data-with-file-and-data
Source: stackoverflow.com
Related Query
- NodeJS/Restify: How can I recieve file upload in API?
- How do you encode a file to base64 then upload as multipart file to backend api using JS?
- How can I upload file from React to Express server?
- How do convert a datauri element into a file I can upload via react?
- How can I check the type of an upload file using Laravel + React?
- How to make query api for email that I can find data email wise for different users from mongoDB with expressJs , nodeJs
- How can I make an image file appear by default in my Upload component? (React.js)
- How can grab my local image path, convert it it to a File object and then upload it to firebase?
- How to upload file to Django rest framework API using Axios and react hook form?
- How to upload a file to MySQL database using Nodejs backend and display the photo
- ReactJS + Redux: How to use Mozilla File API to select local image and upload it to web?
- How can I access my context API state in react app.js file
- How to get the path of the file I selected in a form of input file so I can upload with cloudinary the server side
- How can I get images in react from nodeJS API server
- How to upload image file using ReactJS to api using NestJS with bytea datatype
- Can upload file getting undefined value in using formData and express. How to solve?
- Upload File Api request works in postman but not in nodejs and react MERN
- How to enable file upload on React's Material UI simple input?
- How can I render HTML from another file in a React component?
- ReactJS: How to handle Image / File upload with Formik?
- How can I parse through local JSON file in React js?
- How can I add live-reload to my nodejs server
- How can I set initial React state from API data?
- How can I enable react-i18n translation file to be used in the unit tests done with react-testing-library and jest?
- using css modules, how can I import classes from a file
- How can i get window.location.pathname on my test file using Jest?
- How to read and upload a file in reactjs using custom button
- How can I use a config file in React?
- How to download a file through an API in React?
- next.js file upload via api routes / formidable - not working
More Query from same tag
- Webpack 3 failing on JSX syntax
- Node js, converting Json data into Html format
- Display a different default value after selected an option
- Redirect to login is always triggered because there is a delay from useContext()
- React Material UI randomize/remove MUI class names
- Each child in an array or iterator should have a unique "key" prop in reactjs
- Triggering transition on componentDidMount
- Passing event and props from child to parent in react
- Best practises React hooks HTTP loading
- Reactjs-rails troubles with pre-rendering
- Update FireStore Document on Read
- How to make multiple HTTP requests with RxJS and merge the response into one payload and map it to another action?
- How can I store the data from scanning a QR code in an array using react?
- Reduce lag of displaying value on textfeild when binding onChange event for getting value in React
- Json placeHolder API - Fetch Data white condition
- React/JS - Dynamically render image
- React-router server-side rendering and ajax fetching data
- Setting interval on componentDidMount in reactjs is an correct approach?
- How to get searched word or params in URL
- To do list making with React hooks
- Remotely load <track> element in HTML video
- How to get queryString from url?
- useEffect cleanup on unmount with dependencies
- Counter no less than 0 using react hooks
- How can I get an input's value on a button click in a Stateless React Component?
- How to test the negative actions on a test? Like when a call to the API fails
- Get current user's profile with rails and react
- "activeStyle" attribute always applying on links to pages\index.js
- React.js: How to delete row from an ag grid?
- How to pass information to nested components in react?