Exporting formData from React to Spring boot backend - javascript

React code for build jsonBlob object
function jsonBlob(obj) {
return new Blob([JSON.stringify(obj)], {
type: "application/json",
});
}
exportFTP = () => {
const formData = new FormData();
formData.append("file", jsonBlob(this.state.ipData));
alert("Logs export to FTP server")
axios({
method: "post",
url: "http://localhost:8080/api/auth/uploadfiles",
data: formData,
headers: {
Accept: "application/json ,text/plain, */*",
"Content-Type": "multipart/form-data",
},
});
};
Spring boot backend that accepts for frontend request
public class UploadFile {
#Autowired
private FTPClient con;
#PostMapping("/api/auth/uploadfiles")
public String handleFileUpload(#RequestParam("file") MultipartFile file) {
try {
boolean result = con.storeFile(file.getOriginalFilename(), file.getInputStream());
System.out.println(result);
} catch (Exception e) {
System.out.println("File store failed");
}
return "redirect:/";
}
I want to figure out when I called the function from the frontend it's working properly but I change the state its doesn't send the object to the backend while the file appears in the directory. if I delete the file then only send it again and save it on the directory.
How I save multiple files while doesn't delete the previous ones
Thank you very much for your time and effort.

"Content-Type": "multipart/form-data",
Don't set the Content-Type yourself when posting a FormData.
The Content-Type needs to contain the boundary value that's generated by a FormData(example: multipart/form-data; boundary=----WebKitFormBoundaryzCZHB3yKO1NSWzsn).
It will automatically be inserted when posting a FormData instance, so leave this header out.
When you append blobs to a formdata then it will default the filename to just "blob"
On the backend you seems to override the file all the time:
con.storeFile(file.getOriginalFilename(), file.getInputStream());
Generate a new unik name if you want to keep all files
of topic but why not go with the fetch api? Smaller footprint. don't require a hole library...
fetch('http://localhost:8080/api/auth/uploadfiles', {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json ,text/plain, */*'
}
})

In React application I used props to pass the file name from a different state and make sure to remove,
"Content-Type": "multipart/form-data",
Main function in React,
exportFTP = ({props from different state}) => {
const formData = new FormData();
formData.append("file", jsonBlob(this.state.ipData),{You can use this parm for pass name});
alert("Logs export to FTP server")
axios({
method: "post",
url: "http://localhost:8080/api/auth/uploadfiles",
data: formData,
headers: {
Accept: "application/json ,text/plain, */*"
},
});
};
And back end code I used same to get the original name then Its appears with the right name.
con.storeFile(file.getOriginalFilename(), file.getInputStream());
Chears !!

Related

Using HTTP in NativeScript to send Post-data to a TYPO3-Webservice

I'm trying to send form data from a NativeScript app to a TYPO3-Webservice.
This is the JavaScript I'm using:
httpModule.request({
url: "https://my.domain.tld/webservice?action=login",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({
username:username,
password:password
})
}).then((response) => {
console.log("got response");
console.log(response.content);
//result = response.content.toJSON();
callback(response.content.toJSON());
}, (e) => {
console.log("error");
console.log(e);
});
But I can't read this data in the controller. Even with this:
$rest_json = file_get_contents("php://input");
$postvars = json_decode($rest_json, true);
$postvars is empty. $_POST is empty, too (which is - according to some docs - because the data is sent as JSON and thus the $_POST-Array isn't populated.
Whatever I do, whatever I try, I can't get those variables into my controller.
I tried it with fetch as well as with formData instead of JSON.stringify, same result.
I might have to add, that when I add the PHP-part in the index.php of TYPO3, $postvars is being populated. So I guess something goes missing, until the controller is called.
Any ideas?
the nativescript part seems ok, your problem must be corrected in the server side.
i use similare call and its works
// send POST request
httpModule.request({
method: "POST",
url: appSettings.getString("SERVER") + '/product/list',
content: JSON.stringify(data),
headers: {"Content-Type": "application/json"},
timeout: 5000,
}).then(response => { // handle replay
const responseAsJson = response.content.toJSON();
console.log('dispatchAsync\n\tresponse:', responseAsJson);
}, reason => {
console.error(`[ERROR] httpModule, msg: ${reason.message}`);
});

JS: axios POST with large nested object and form-data

I am to post an Axios request because using get results in a 414 error.
Here's the object:
rows= {
0 : {
"name":"Thor",
"status":"active",
"email":"somuchlightning#kaboom.io",
},
1 : {
"name":"Mesa",
"status":"active",
"email":"big-mesa#tundra.com",
},
2 : {
"name":"Jesper",
"status":"stdby",
"email":"jes#slap.net,
},
}
This is just a sample of the object's format. There is 400+ elements in the real one, thus post instead of get. I am having trouble properly building the form-data on this one. Here's what I have:
let data = new FormData();
Object.keys(rows).forEach(key => data.append(key, rows[key])); // <--- this doesn't do
data.set('target', target); // <---- this comes through just fine
axios({
method: 'post',
url: 'byGrabthorsHammer.php',
data: data,
headers: {'Content-Type': 'multipart/form-data'}
}).then(function(response) {
if (response.error) {
console.log('failed to send list to target');
console.log(response);
} else {
console.log('response: ');
console.log(response);
}
});
What comes through is just [Object][Object]' when ivar_dump($_POST);`. This is not what I want. How could I rewrite this properly so I get the data to the other side (like GET...).
Yow bro, POST Are for inserting new stuff, instead of doing a post you need a patch
axios.patch it is basically the same. And it won’t fix your issue.
To fix the issue you need to set the Content-Type to application/json, then on yow
axios.post(url, data: JSON.stringify(bigObject))
.then(Rea=>Rea)
You could try stringifying the data. JSON.stringify(data)

How to disable caching on get call?

I would like to disable cache on getting a request in vue environment. I already tried this but it does not work.
api.js (file)
getCall: () => {
return performAsyncGet(apiConfig.getCall.url,
requestConfigJSON, _REQUEST_TOKENS.getCall, apiConfig.getCall.cache)
.then(
response => response.data
);
},
(apiConfig.js) (file)
getCall: {
url: `${servicePathPrefixOrDomain}/api/getCall`
cache: false
}
Does anybody know how to disable the cache, when making a get request in vue.js?
Thanks in advance!
To avoid caching you can make your url unique by appending timestamp as a querystring parameter like this:
getCall: {
url: `${servicePathPrefixOrDomain}/api/getCall?_t={new Date().getTime()}`
cache: false
}
In this way for every ajax call the url will be unique due to different timestamp and browser will not cache the response.
Is solved adding the next code in the header:
const requestConfigJSON = {
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
}
};

Upload form data fails with axios

I have a form with multiple fileds, which one is a file input. I use axios to upload the file under a separate attribute:
axios.post(ENDPOINT,{
form: formData,
image: image
}, getAuthorizationHeader())
function getAuthorizationHeader() {
return {
headers: {
'Authorization': //...,
'Content-Type': undefined
}
};
}
formData is created like this:
let formData = new FormData();
formData.append('title', values.title);
formData.append('description', values.description);
formData.append('amount', values.amount);
And the image is:
Under the network tab of the Chrome Dev tool, When I look at the request, it looks like this:
As you can see in the screenshot, the file is empty? The CONTENT-TYPE is application/json which is not what I expected. I expected browser to detect the CONTENT-TYPE as multipart/form-data
What is wrong here?
First of all, image should be part of the formData:
formData.append('image', <stream-of-the-image>, 'test.png')
Secondly, formData should be the second parameter of axios.post:
axios.post(ENDPOINT, formData, getAuthorizationHeader())
Last but no least, you should merge formData.getHeaders():
function getAuthorizationHeader() {
return {
headers: Object.assign({
'Authorization': //...,
}, formData.getHeaders())
};
}
Sample code for your reference: https://github.com/tylerlong/ringcentral-js-concise/blob/master/test/fax.spec.js

How to set a header for a HTTP GET request, and trigger file download?

Update 20140702:
The solution
Detailed answer as a blog post
(but I'm marking one of the other answers as accepted instead of my own,
as it got me halfway there, and to reward the effort)
It appears that setting a HTTP request header is not possible through links with <a href="...">, and can only be done using XMLHttpRequest.
However, the URL linked to is a file that should be downloaded (browser should not navigate to its URL), and I am not sure is this can be done using AJAX.
Additionally, the file being returned is a binary file, and AJAX is not intended for that.
How would one go about triggering a file download with a HTTP request that has a custom header added to it?
edit: fix broken link
There are two ways to download a file where the HTTP request requires that a header be set.
The credit for the first goes to #guest271314, and credit for the second goes to #dandavis.
The first method is to use the HTML5 File API to create a temporary local file,
and the second is to use base64 encoding in conjunction with a data URI.
The solution I used in my project uses the base64 encoding approach for small files,
or when the File API is not available,
otherwise using the the File API approach.
Solution:
var id = 123;
var req = ic.ajax.raw({
type: 'GET',
url: '/api/dowloads/'+id,
beforeSend: function (request) {
request.setRequestHeader('token', 'token for '+id);
},
processData: false
});
var maxSizeForBase64 = 1048576; //1024 * 1024
req.then(
function resolve(result) {
var str = result.response;
var anchor = $('.vcard-hyperlink');
var windowUrl = window.URL || window.webkitURL;
if (str.length > maxSizeForBase64 && typeof windowUrl.createObjectURL === 'function') {
var blob = new Blob([result.response], { type: 'text/bin' });
var url = windowUrl.createObjectURL(blob);
anchor.prop('href', url);
anchor.prop('download', id+'.bin');
anchor.get(0).click();
windowUrl.revokeObjectURL(url);
}
else {
//use base64 encoding when less than set limit or file API is not available
anchor.attr({
href: 'data:text/plain;base64,'+FormatUtils.utf8toBase64(result.response),
download: id+'.bin',
});
anchor.get(0).click();
}
}.bind(this),
function reject(err) {
console.log(err);
}
);
Note that I'm not using a raw XMLHttpRequest,
and instead using ic-ajax,
and should be quite similar to a jQuery.ajax solution.
Note also that you should substitute text/bin and .bin with whatever corresponds to the file type being downloaded.
The implementation of FormatUtils.utf8toBase64
can be found here
Try
html
<!-- placeholder ,
`click` download , `.remove()` options ,
at js callback , following js
-->
<a>download</a>
js
$(document).ready(function () {
$.ajax({
// `url`
url: '/echo/json/',
type: "POST",
dataType: 'json',
// `file`, data-uri, base64
data: {
json: JSON.stringify({
"file": "data:text/plain;base64,YWJj"
})
},
// `custom header`
headers: {
"x-custom-header": 123
},
beforeSend: function (jqxhr) {
console.log(this.headers);
alert("custom headers" + JSON.stringify(this.headers));
},
success: function (data) {
// `file download`
$("a")
.attr({
"href": data.file,
"download": "file.txt"
})
.html($("a").attr("download"))
.get(0).click();
console.log(JSON.parse(JSON.stringify(data)));
},
error: function (jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
}
});
});
jsfiddle http://jsfiddle.net/guest271314/SJYy3/
I'm adding another option. The answers above were very useful for me, but I wanted to use jQuery instead of ic-ajax (it seems to have a dependency with Ember when I tried to install through bower). Keep in mind that this solution only works on modern browsers.
In order to implement this on jQuery I used jQuery BinaryTransport. This is a nice plugin to read AJAX responses in binary format.
Then you can do this to download the file and send the headers:
$.ajax({
url: url,
type: 'GET',
dataType: 'binary',
headers: headers,
processData: false,
success: function(blob) {
var windowUrl = window.URL || window.webkitURL;
var url = windowUrl.createObjectURL(blob);
anchor.prop('href', url);
anchor.prop('download', fileName);
anchor.get(0).click();
windowUrl.revokeObjectURL(url);
}
});
The vars in the above script mean:
url: the URL of the file
headers: a Javascript object with the headers to send
fileName: the filename the user will see when downloading the file
anchor: it is a DOM element that is needed to simulate the download that must be wrapped with jQuery in this case. For example $('a.download-link').
i want to post my solution here which was done AngularJS, ASP.NET MVC. The code illustrates how to download file with authentication.
WebApi method along with helper class:
[RoutePrefix("filess")]
class FileController: ApiController
{
[HttpGet]
[Route("download-file")]
[Authorize(Roles = "admin")]
public HttpResponseMessage DownloadDocument([FromUri] int fileId)
{
var file = "someFile.docx"// asking storage service to get file path with id
return Request.ReturnFile(file);
}
}
static class DownloadFIleFromServerHelper
{
public static HttpResponseMessage ReturnFile(this HttpRequestMessage request, string file)
{
var result = request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(file, FileMode.Open, FileAccess.Read));
result.Content.Headers.Add("x-filename", Path.GetFileName(file)); // letters of header names will be lowercased anyway in JS.
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(file)
};
return result;
}
}
Web.config file changes to allow sending file name in custom header.
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="POST,GET,PUT,PATCH,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Authorization,Content-Type,x-filename" />
<add name="Access-Control-Expose-Headers" value="Authorization,Content-Type,x-filename" />
<add name="Access-Control-Allow-Origin" value="*" />
Angular JS Service Part:
function proposalService($http, $cookies, config, FileSaver) {
return {
downloadDocument: downloadDocument
};
function downloadFile(documentId, errorCallback) {
$http({
url: config.apiUrl + "files/download-file?documentId=" + documentId,
method: "GET",
headers: {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer " + $cookies.get("api_key")
},
responseType: "arraybuffer"
})
.success( function(data, status, headers) {
var filename = headers()['x-filename'];
var blob = new Blob([data], { type: "application/octet-binary" });
FileSaver.saveAs(blob, filename);
})
.error(function(data, status) {
console.log("Request failed with status: " + status);
errorCallback(data, status);
});
};
};
Module dependency for FileUpload: angular-file-download (gulp install angular-file-download --save). Registration looks like below.
var app = angular.module('cool',
[
...
require('angular-file-saver'),
])
. // other staff.
Pure jQuery.
$.ajax({
type: "GET",
url: "https://example.com/file",
headers: {
'Authorization': 'Bearer eyJraWQiFUDA.......TZxX1MGDGyg'
},
xhrFields: {
responseType: 'blob'
},
success: function (blob) {
var windowUrl = window.URL || window.webkitURL;
var url = windowUrl.createObjectURL(blob);
var anchor = document.createElement('a');
anchor.href = url;
anchor.download = 'filename.zip';
anchor.click();
anchor.parentNode.removeChild(anchor);
windowUrl.revokeObjectURL(url);
},
error: function (error) {
console.log(error);
}
});

Categories