File upload issue in Mongoose - reactjs

I am using Mongoose 6.18 version as an Embedded Web Server for my project. I have an issue when I try to upload a file to the server. I have a react application on the front end that uses axios api with formdata to send the file. ``
await axios.post("http://" + window.location.host + "/upload", data, {
headers: {
"Content-Type": "multipart/form-data",
"Content-Length": ""
}
}).then((response) => {
console.log(response);
console.log(response.data.message);
alert("File Upload successful");
}, (error) => {
console.log(error);
alert("File Upload not successful");
});
On the server side I am using multipart handling as mentioned in this link. I use the function mg_file_upload_handler.
https://cesanta.com/blog/big-upload-example-mongoose-more-than-an-embedded-web-server-2/
By connection closes when the multipart chunks are in progress and every time only a part of file is uploaded. Can someone pls guide me in this.

Please use the latest version instead of an old 6.18, and use of the several upload methods, as described in the tutorial https://mongoose.ws/tutorials/file-uploads/

Related

How to upload local video file to Google Cloud

I am stuck with a file upload process in a react app. In the app, I am trying to upload local video files to Google Cloud Storage.
I take the input file from:
<input type={`file`} accept=".mp4" onChange={VideoSelectChangeFunc} />
In VideoSelectChangeFunc, I get the local URL of the input file by,
let file = URL.createObjectURL(event.target.files[0])
Then I use it in axios to send to cloud
export const UploadVideo = async (file, signedurl, asset_uuid) => {
let resultState = { state: '', data: {} };
await axios({
method: 'put',
url: signedurl,
data: file,
headers: {
'Content-Type': 'application/octet-stream',
},
}).then(function (response) {
resultState.state = 'success';
resultState.data = response.data
}).catch(function (error) {
resultState.state = 'error';
resultState.data.message = error.message;
window.toastr.error(error.message);
console.log(error)
})
return resultState;
}
What I see on cloud is:
blob:http://localhost:3000/9b650cbf-8b49-440b-9e90-da6bdb5d392a
This is just the local URL of the file as string but not the video itself, when I copy and paste it on browser I can see the video. I searched the situation and saw 'Content-Type': 'blob' would solve the problem. However, we are checking headers in our CORS Policy, so it has to be 'Content-Type': 'application/octet-stream'. Is there a way to work this out?
Before sending it, converting the blob url into file worked. I have only added these two lines then, called axios.
let blob = await fetch(blobURL).then(r => r.blob());
var file = new File([blob], "thisVideo.mp4",{type:"video/mp4", lastModified:new Date().getTime()})
This can be useful, in the situations where the file is not uploaded right away but the url saved temporarily to be called later on which was the case here. If you are interested visit this question too:
How to get a file or blob from an object URL?

'Failed to fetch' error when downloading files that has more than 10mb React + Spring boot

Have a client-side server in react that need to request files from backend server (kotlin + spring boot) to download them.
Using the request endpoint in Swagger, Postman and Insomnia, i can success download any file with any size.
In my client-side server, have a list of this files that download can be triggered by a click in an icon. I can download files that has less than 10mb with no error, but when file has more than 10mb, it fails with Failed to fetch error.
Actually, it's a weird behavior. Let say i have a file named FILE A that has under than 10mb and FILE B with 25MB (is the max size allowed to upload). In first entried of the page, if i first request to download FILE B, it throw Failed to fetch. Now, if first request is in FILE A and after FILE B, FILE B download is successed. I'm really confused what is going on here.
Code:
const options = {
method: 'GET',
headers: { "Authorization": `Bearer ${user?.token}` },
};
fetch(`http://localhost:8080/storage/download?fileName=${filePath}`, options)
.then(function (response) {
return response.blob();
})
.then(function (myBlob) {
setSpinControl(false);
const file = new Blob(
[myBlob],
{ type: 'application/pdf' }
);
const fileURL = URL.createObjectURL(file);
if (window) {
window.open(fileURL, '_blank');
}
})
.catch((err) => {
setSpinControl(false);
console.log(err)
});
Already tried some alternatives:
Using axios (throw Network Error);
Using libraries as file-saver;
Setting timeout to 9999999;
All achieve same behavior.
I read too that createObjectURL uses memory to perform download, but max size of a file is validated to be 25MB.
Some print of Network tab:
Request Header:
Request Response:
Network List:
Any tips what i can do here?

How to Download Pdf File in React From Api

I want to download pdf file by fetching from Flask db.
React code:
downloadReport(idx) {
console.log(idx)
fetch('/getDataReport', {
method: 'post',
headers: {'Content-Type':'application/json', 'Accept':'application/json', 'responseType':'arraybuffer'},
body: JSON.stringify({id: idx}),
}).then(res => res.json()).catch(error => {
console.error('Error:', error);
})
.then(response => {
console.log(response)
})
}
The above is triggered by onClick method, I get the id and put it in API body. When I give the id I want to make it download from db.
Flask code:
def getData():
req = flask.request.get_json(force=True)
id = req.get('id', None)
report = Report.query.filter_by(id=id).first()
return send_file(BytesIO(report.get_data()), attachment_filename=report.get_date()+'-report.pdf', as_attachment=True)
When I click download, Post request working fine actually. But I get "index.js:1437 Error: SyntaxError: Unexpected token % in JSON at position 0" error and my response is undefined. I couldn't solve it. Hope someone can help. Thank you in advance.
reactjs
I'd start by looking at the line where you're attempting to deserialize the response as JSON:
.then(res => res.json())
Typically when fetching a file from an endpoint, the response is handled as a blob:
.then(res => res.blob()).then((blob) => { // do what you need to do })
blob() MDN Documentation
Once you've gotten the file, then you'll need a mechanism to force the browser to download the file. There are a few NPM packages that can help with this such as downloadjs or you can roll your own.
Another StackOverflow post on the same topic

POST Request to Azure DevOps Rest API with Reactjs

So far I've been able to configure a method in C# that is able to hardcode a new repository in Azure DevOps, but my real goal is to create a user interface that allows the user to specify the request body which consists of the following:
name: 'nameOfRepository',
project: {
id: 'projectId'
}
The user will fill out the first input field with the desired name of the new repository. The second input field should use a GET Request that displays all available projects in your organization in a dropdown list.
I'm also using .NET Core 3.0 and believe this probably has to be done with an API controller as well, but I am not certain.
I have little to no experience with React and have no idea how and where I'm going to specify the request body and personal access token to create the repository. I would appreciate an explanation of how this works and would also appreciate a solution that could guide me in the right direction.
Azure DevOps Rest API Documentation will give you access to the platform. If you are decided to develop totally in React js. I would like to suggest to take a starter kit, mostly will cover all your basic setup to React.
Follow the below steps to get an idea of how you can achieve with react js
Need to set up OAuth in azure deops. The below link will give an idea. In the callback page, you need to store access token store
https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops. If you have personal auth token this is not required
Get all list of repositories using fetch or Axios API
Example with Axios:
const headers = {
'Content-Type': 'application/json',
'Authorization': 'bearer token' or 'basic personalaccesstoken'
}
axios.get('https://dev.azure.com/{organization}/{project}/_apis/git/repositories', {
headers: headers,
params: {
'api-version':'5.1'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Use react form to capture the input value and on submit of form, validate against the repositories, if it is new call the Axios or fetch post method to create a new repository
Example with Axios
const headers = {
'Content-Type': 'application/json',
'Authorization': 'bearer token'
}
const data = {
name: ''
parentRepository: {id: '', ....}
project: {id: '', ...}
}
axios.post('https://dev.azure.com/{organization}/{project}/_apis/git/repositories', JSON.stringify(data),
{
headers: headers,
params: {
'api-version':'5.1'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Similarly, you can access all the API's mentioned REST API documentation of Microsoft. link

How to add custom HTTP headers in React application?

I have a react js application. I want to add some http headers in the every response that's being returned from the app. Could you please suggest how to implement this !
NOTE : I am not trying to call any api with headers in request. I want my react app to respond with some custom headers in the response
As Dovlet Mamenov mentioned in the comment, this has to be done on the web server wherever react app is hosted.
For example, If react app is hosted on the Apache server, then these http headers in the response should be added on the Apache server conf.
const header = new Headers();
header.append('Access-Control-Allow-Origin', '*');
const body = {
author: author,
text: text
}
axios.post("https://api.test/posts/create", body, header)
.then((res) => {
this.setState({
result: res
});
})
.catch((error) => {
this.setState({
error: error.message
});
})
You have to use the native object Headers, and add it in axios.

Resources