When downloading a file using ResponseEntity in Spring, byte breaks in reaction - reactjs

This is a method of downloading files from Spring to ResponseEntity.
When you download it, the byte breaks and comes out.
If you use tag a, you can download the file without breaking it, but it is difficult to put the event after downloading the file using response.
Is there a way?
// Spring
Resource resource = qnaService.loadAsResource(tempFileName);
File file = resource.getFile();
if (file.exists()) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
headers.set("Content-Transfer-Encoding", "binary");
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + OriginFileName)
.contentType(MediaType.APPLICATION_XML)
.contentLength(file.length())
.body(new InputStreamResource(new FileInputStream(file)));
}
// React
const data = await request({
url: `/api/qna/file/test/${node.qnaFileID}`,
method: request.method.get(),
});
console.log(data);
const blob = new Blob([data], { type: 'application/xml;charset=utf-8' });
saveAs(blob, node.name);
// Data is broken.
data: "�PNG\r\n\u001a\n\u0000\u0000\u0000\rIHDR\u0000\u0000\t�\u0000\u0000\u0004z\b\u0006\u0000\u0000\u0000�س]\u0000\u0000\fliCCPICC Profile\u0000\u0000H��W\u0007XS�\u0016�[RIh\u0001\u0004���\u0004�\u001a#J\b-��"�\bI �Ę\u0010T�eQ���\b��U\u0011Ŷ\u0002bǮ,��/\u0016T�uQ\u0017\u0

just add responseType: blob to your request

Related

Loading xslx file from server to React

Dear fellow developers!
Tell me how to transfer a file with the .xlsx extension from the Spring backend to the React frontend?
Let's get my code first. This is my backend controller which returns a ByteArrayResource:
#PostMapping("/download-report")
public ResponseEntity<ByteArrayResource> generateReport(#RequestBody ReportAttributesWithFiltersDto attributesWithFilters) {
var resource = reportBuilder.generateReport(attributesWithFilters);
var headers = getReportHeaders();
return new ResponseEntity<>(resource, headers, HttpStatus.CREATED);
}
private HttpHeaders getReportHeaders() {
var contentDisposition = ContentDisposition.builder("attachment")
.filename("attachment; filename=my_file.xlsx")
.build();
var headers = new HttpHeaders();
headers.setContentType(new MediaType("application", "force-download"));
headers.setContentDisposition(contentDisposition);
return headers;
}
The backend performs well, if you test it in the development environment, it will return the file in response.
The file downloads fine and there are no problems. Backend shouldn't be a problem.
The problems start when I upload the file on the frontend.
Here is my request:
downloadReport: builder.mutation({
query: (body) => ({
url: paths.downloadReport,
method: "POST",
body: body,
responseHandler: "blob",
}),
}),
What nonsense I get in response, this is some kind of nightmare!
In the case of using a blob, I get this:
res:
data:
undefined
If I set responseHandler: "text", then I get this:
{
"data": "PK\u0003\u0004\u0014\u0000\b\b\b\u0000�,U\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0013\u0000\u0000\u0000[Content_Types].xml�S�n�0\u0010����*6�PU\u0015�C\u001f�\u0016��\u0003\\{�X�%����]\u00078�R�\nq�cfgfW�d�q�ZCB\u0013|��|�*�*h㻆},^�{Va�^K\u001b<4�\u00076�N\u0016�\bXQ�dž�9�\u0007!P��$�\u0010�\u0013҆�d�c�D�j);\u0010��ѝP�g��E�M'O�ʕ����H7L�h���R���G��^�'�\u0003\u0007{\u0013�\b�zސʮ\u001bB��3\u001c�\u000b˙��h.�h�W�жF�\u000ej娄CQՠ똈���}ιL�U:\u0012\u0014D�\u0013����%އ����,�B���[�\t��\u001e ;˱�\t�{N��~��X�p�\u001cykOL�\u0004\u0018�kN�V��ܿBZ~����q\u0018��\u000f �a\u0019\u001fr��{O�\u0001PK\u0007\bz��q;\u0001\u0000\u0000\u001c\u0004\u0000\u0000PK\u0003\u0004\u0014\u0000\b\b\b\u0000�,U\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u000b\u0000\u0000\u0000_rels/.rels���j�0\f�_���8�`�Q��2�m��\u00014[ILb��ږ���.[K\n\u001b�($}�\u0007�v?�I�Q.���uӂ�h���\u001bx>=��#\u0015��p�H\u0006\"�~�}�\t�n����*\"\u0016\u0003�H�׺؁\u0002��\u0013���8\u0007�Z�^'�#��7m{��O\u0006�3��\u0019�G�\u0006u�ܓ\u0018�'��y|a\u001e�����D�\t��\u000el_\u0003EYȾ�\u0000���vql\u001f3�ML�eh\u0016���*�\u0004��\\3�Y0���oJ׏�\u0003\t:\u0014��^\b�\u001f�}\u0002PK\u0007\b��z��\u0000\u0000\u0000I\u0002\u0000\u0000PK\u0003\u0004\u0014\u0000\b\b\b\u0000�,U\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0010\u0000\u0000\u0000docProps/app.xmlM��\n�0\u0010D��\u0010ro�z\u0010�4� �'{�\u000f\b��\u0006�MHV�盓z�\u0019��T��E�1e\u0017�����\u0002Ɇ�ѳ����:�No7jH!bb�Y�\u0007�V���\u0004�����T�)$o���0M��9ؗGb�7�\u0001pe�\u0011�*~�R�>��Y�EB��\u0014�\u0018nW\u0005������\u0000PK\u0007\b6n�!�\u0000\u0000\u0000�\u0000\u0000\u0000PK\u0003\u0004\u0014\u0000\b\b\b\u0000�,U\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0011\u0000\u0000\u0000docProps/core.xmlm��J�0\u0010F_�依�EqC�E�\u0005Aq���w!\u0019�b�C\u0012����u���%��\u001c&_�=�1yG�\u0007�kB��$�����j����\u000b������X\u0013mȶ��e�8�;cх\u0001}\u00125�3ak҇`\u0019�\u0017=*�H�\u0018�\u0018�x�Wׁ��w\bE�����%\u000f\u001cfajW#9)�X��͍�#\n�\u0011\u0015���f\u0014~؀N�\u0007�d%�~X�i���\\��\u0011����ò|:���\u0002IS��L8�\u0001e\u0012\u0005,|���w�T^]�;�\u0014yQ��&�EK7����=W�k~\u0016~��k.c!=&����[�+�Ss�\tPK\u0007\bȂ`�\u0005\u0001\u0000\u0000�\u0001\u0000\u0000PK\u0003\u0004\u0014\u0000\b\b\b\u0000�,U\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0014\u0000\u0000\u0000xl/sharedStrings.xml���J�#\u0014����0d�Bҙ&��!M�\u001b��ӕ�(5�\u0001��L�.�\".*\u0016ԅ��}�x)F{�\u0015μ�'��4\u0005e`����?�93F��9 G��m�-J�\u0014���V�=ۭ\u0016���5Y�J����y#*^�\rP��Hõ\u000f\u001b��$��\bڸ�(Ղ��S�+5�)�W�\\��{�S\u000e�ӯR^���\u001e�YV�\u001cP��\u001cuʶ+�\u0006�M#0�+�a�+$Ї\b\u000f�8�Р�i�X2��#\b}q=3w\u0007a\u001c'�\u0014F�\u000eo(\u001d�M{Z��B0\u001d�6��'D\t�{\u0018�6\u0011\u0017��G�\b]^g���;Z��#���\b��&�H�#�J\u000f�3q���gl�j:�0E�YAN+[鬮j��R�VP��E����6|\u001c1��x�;ޝ�}scI��Y��-�D\u0013YZ�A\u0010{<\"q..\u0012‡x�\u0005x\u0014MD|\u0013��?\bU=SHi�\\.���P�d\u0013���\u000f�'.q\u000f�7���������,N�\u0019�5��_�\u0014\u001f��\rPK\u0007\b��-��\u0001\u0000\u0000�\u0002\u0000\u0000PK\u0003\u0004\u0014\u0000\b\b\b\u0000�,U\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\r\u0000\u0000\u0000xl/styles.xml���n� \u0010��J}\u0007���d���&C%W��J]�9ۨpX#\"�O_0N�L\u001d:����\u001f���n4���ye���UA\t`c�®�\u001f��iKw���aҰ�\u0001\u0002�\u000e�\u0015�C\u0018^\u0018�M\u000fF��\u001d\u0000�Ik�\u0011!��c~p �O&�٦(��\u0011\n)/�dj\u0013<i�\tCE\u000b�x�Z�*k�\u0005^�or\u0016:*i���Xm\u001dQ(a\u0004Y�m�P\u0018�]�B��S3O\u0018��,o�0O��\u0019��%��[��Ii�;Ćf���\b\u0001\u001cֱ K~�\u0006�(Z�������}�91�8�\u0010/>Z'�\u0016nߟ%^jhC48��)\u0006;�t\u0018�51�Jt\u0016�NȋcI\"�\u0001��iu��\u001d{lI���L����_�8ВfL.\u0012�����ƒ����hv���\u000fPK\u0007\b����E\u0001\u0000\u0000�\u0002\u0000\u0000PK\u0003\u0004\u0014\u0000\b\b\b\u0000�,U\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u000f\u0000\u0000\u0000xl/workbook.xml���N�0\u0010�w$�����\u0001� ��\u0005!uc(�}i��v�3-s\u0017ނ��=�7�I\u0015`d:��������\u001e#��%\u0014\u000b\u0001\f�\u000e��������=,�ˋ�\u0010�n\u0013Žeޓ�6���t�N�\"���\tѩ�c�r�#*C-br\u001d�\u0016�;e=�\re��#4���\u0018��C�Β��J�-��'��=GfT��A�JhTG\b���ͫ�\u0003��cdJ'�ǵ�H\u0010#���S�y2�\u001cJ8}\u000e����5\u001c���\u001a\tqen�M�*�b�̧|~V\u0003PK\u0007\b\u0007$�h�\u0000\u0000\u0000b\u0001\u0000\u0000PK\u0003\u0004\u0014\u0000\b\b\b\u0000�,U\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u001a\u0000\u0000\u0000xl/_rels/workbook.xml.rels��Mk�0\f#���}q��\u0018�n/c����\u0000c+qh\"\u0019K�迟���#\u0007;�$��{\u000f��~Γy�\"#���i� \u0005�#\r\u000e^�O7�`D=E?1�\u0003b�n��8y�?$�YLE�8H���Z\t\tg/\rg����^�\f6�p�\u0003�U���r΀%�좃��\u001d��/\u0003�\u0003I�`|�Rˤ��:f����~\f���mF�\u000bv����\u001c�:���ׯ�������p9HB�Sy\u001dݵK~\u0004�\u0018����\u000bPK\u0007\b�\u0003;��\u0000\u0000\u00003\u0002\u0000\u0000PK\u0003\u0004\u0014\u0000\b\b\b\u0000�,U\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0018\u0000\u0000\u0000xl/worksheets/sheet1.xml��[�� \u0018���?\u0010�+��э��vִ\u0017M6=^3����\u0001fܟ_p\fE�l:���<|/�|���e���rѱ1���B#ǒU��d����]\f��oҙ�g�R*�*\u0018E\u0006[)�;�D�ҁ\b�MtT�f| RMy���)����G�u#4�n�yZu\u0003\u001d����:�\u000f�]�C����\u001f\u001d��5\u0006z�\u0013c�z�ʠR�������T�%?S]��(/\u0016�'\u000e*Z�s/���#�V�/\rէ����b�\u0005C�\u000f\u0000���,�sW�V�\u0002'�q�F8��<\u000bɆ�W��\u000bNTȢ��5L\u0016^���:8����?�\u001a�Q��\n\u0012'v�(�9*X�\u0002\u0013�8��q\nנ�>�$H�w�T�fE&\u000b�ο\u001f9�vq���H���̀�6�M��A5T\u0015\b5��n�.�he�m�m�\u0007��-;��߲G�\u0005[V�,4\f)g#��8^\u0016�W9��ݱ�\u0015��mvع�,޹�,ٹ��s�.�\u001by�uy�\u0015y�y��\u001c7pז�\r�����`珬\u001b4��~&��F\u0001NL�;�^\u001eG��1I����V=qf��Z.� ��gf\u0019K6������4�\u0005PK\u0007\b�Q�.�\u0001\u0000\u0000}\u0005\u0000\u0000PK\u0001\u0002\u0014\u0000\u0014\u0000\b\b\b\u0000�,Uz��q;\u0001\u0000\u0000\u001c\u0004\u0000\u0000\u0013\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000[Content_Types].xmlPK\u0001\u0002\u0014\u0000\u0014\u0000\b\b\b\u0000�,U��z��\u0000\u0000\u0000I\u0002\u0000\u0000\u000b\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000|\u0001\u0000\u0000_rels/.relsPK\u0001\u0002\u0014\u0000\u0014\u0000\b\b\b\u0000�,U6n�!�\u0000\u0000\u0000�\u0000\u0000\u0000\u0010\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000�\u0002\u0000\u0000docProps/app.xmlPK\u0001\u0002\u0014\u0000\u0014\u0000\b\b\b\u0000�,UȂ`�\u0005\u0001\u0000\u0000�\u0001\u0000\u0000\u0011\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000i\u0003\u0000\u0000docProps/core.xmlPK\u0001\u0002\u0014\u0000\u0014\u0000\b\b\b\u0000�,U��-��\u0001\u0000\u0000�\u0002\u0000\u0000\u0014\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000�\u0004\u0000\u0000xl/sharedStrings.xmlPK\u0001\u0002\u0014\u0000\u0014\u0000\b\b\b\u0000�,U����E\u0001\u0000\u0000�\u0002\u0000\u0000\r\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000�\u0006\u0000\u0000xl/styles.xmlPK\u0001\u0002\u0014\u0000\u0014\u0000\b\b\b\u0000�,U\u0007$�h�\u0000\u0000\u0000b\u0001\u0000\u0000\u000f\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0010\b\u0000\u0000xl/workbook.xmlPK\u0001\u0002\u0014\u0000\u0014\u0000\b\b\b\u0000�,U�\u0003;��\u0000\u0000\u00003\u0002\u0000\u0000\u001a\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u00006\t\u0000\u0000xl/_rels/workbook.xml.relsPK\u0001\u0002\u0014\u0000\u0014\u0000\b\b\b\u0000�,U�Q�.�\u0001\u0000\u0000}\u0005\u0000\u0000\u0018\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000R\n\u0000\u0000xl/worksheets/sheet1.xmlPK\u0005\u0006\u0000\u0000\u0000\u0000\t\u0000\t\u0000?\u0002\u0000\u0000�\f\u0000\u0000\u0000\u0000"
}
What can I be doing wrong?
ok guys,
I found the answer to my question. The thing is, I was using Redux for the request. For some reason it didn't load my file.
Now I switched to fetch request and everything started working
const requestReport = (selectedObj) => fetch(`/api/reports/download-report`, {
headers: new Headers({'content-type': 'application/json'}),
method: "POST",
body: JSON.stringify(selectedObj),
}).

react springboot file download error (file size increases)

I have small problem while developing react, spring boot application dashboard.
Here is my problem, I developed file upload dashboard it's requests from client (react) to
backend server side (springboot) by axios call multipart-form.
Seem there is no problem on
uploading file to server (because uploaded file opens well inside of server and the file
size is equal).
However, when I downloading the file the file size increases and cannot
open properly (It's shows alarm that the file damaged).
Now I don't know where to find the solution :( plz help me.
here is my react code which has axios call with file name:
function fileDownlod(props) {
api.responseType = 'blob'
api.defaults.headers.common[`Authorization`] = 'Bearer ' + localStorage.getItem('token')
api
.post('/filedown', { uuid: props }, header)
.then((response) => {
const name = response.headers['content-disposition'].split('fileName=')[1]
console.log(response.headers)
console.log(name)
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', name)
link.style.cssText = 'display:none'
document.body.appendChild(link)
link.click()
link.remove()
})
and this is my spring boot code (where I checked that the file size both equal)
#CrossOrigin(value = {"*"})
#RequestMapping(value = "/filedown", method= {RequestMethod.POST, RequestMethod.GET})
public void fileDown (#RequestBody FileEntity param, HttpServletResponse response) throws Exception {
String fileFullPath = fileLocation + param.getUuid();
try{
Path filePath = Paths.get(fileFullPath);
FileEntity fileEntity = fileRepository.findByUuid(param.getUuid());
if(fileEntity.getContentType().contains("image")){
response.setContentType("multipart/form-data");
}else{
response.setContentType("application/octet-stream");
}
response.setHeader("Content-Disposition", "attachment; fileName=" + URLEncoder.encode(fileEntity.getFileName(),"UTF-8"));
response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader( "Access-Control-Allow-Headers","Content-Disposition");
response.setHeader( "Access-Control-Expose-Headers","Content-Disposition");
byte[] fileByte = FileUtils.readFileToByteArray(new File(fileFullPath));
System.out.println("file size of fileByte: " + fileByte.length);
System.out.println("file size of file inf. from DB: " + fileEntity.getFileSize());
response.getOutputStream().write(fileByte);
response.getOutputStream().flush();
response.getOutputStream().close();
For more information, I'm develeping in macOS and when I deploy the application file download won't work in iphone eihter :( Any suggestion? thank you.
I found my answer by myself the problem was "api.responseType = 'blob'" which didn't work as responseType.
this was my solution below
api
.post('/filedown', { uuid: props }, { responseType: 'blob' }, header)

Spring API request giving "Content type 'application/octet-stream' not supported" error, however request is successful when using Postman

I am trying to send an API request through my React frontend to Spring backend. When I send the request I get this error:
Could not resolve parameter [0] in private org.springframework.http.ResponseEntity com.example.bottlecap.controllers.BottlecapController.entryForm(com.example.bottlecap.domian.Bottlecap,org.springframework.web.multipart.MultipartFile): Content type 'application/octet-stream' not supported
However, when I set up the request using Postman it goes through fine. I presume there may be an issue with how I am setting up my FormData on the React end. However, I have had little luck figuring it out.
My API is supposed to recieve an object that holds data about my submission as well as an image that goes with the submission. In my Postman request, I am creating a form data that holds a JSON file that holds all the object data and a random image just for testing. As I said, the requets goes through fine with this. However, in the frontend code, I am parsing through the object data as Json and adding it to a FormData as well as adding the image to the FormData.
Here is my Spring Controller:
#RequestMapping(path ="/bottlecap/entry", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE})
private ResponseEntity entryForm(#RequestPart("cap") Bottlecap cap, #RequestPart("file") MultipartFile image){
System.out.println(cap);
cap.toString();
System.out.println("Test");
return ResponseEntity.ok().build();
}
Here is my react Frontend form submission handler:
handleSubmit = event =>{
console.log(this.state.page);
console.log(this.state.page);
event.preventDefault();
const cap ={
"name":this.state.name,
"brand":this.state.brand,
"yearMade":parseInt(this.state.yearMade),
"country": this.state.country,
"description":this.state.description,
"yearFound":parseInt(this.state.yearFound),
"isAlcoholic":"true"
};
const stringCap = JSON.stringify({cap});
console.log(cap);
var formData = new FormData();
formData.append('cap', JSON.parse(stringCap));
formData.append('file',this.state.imageFile)
axios.post('http://localhost:8080/bottlecap/entry', formData, {headers:{'Content-Type':'multipart/form-data'}})
.then(res=>{
console.log(res);
console.log(res.data);
//window.location = "/success"
this.setState({pageDone:true})
this.setState({pageLoading:true})
})
}
Here is a screenshot of my Postman request if it may help.
Also here is the contents of the json file I am sending through on Postman, if it may help as well.
{"name":"post-test",
"brand":"post-test",
"yearMade":1000,
"country":"post-test",
"description":"post-test",
"yearFound":1000,
"isAlcoholic":"true"}
The last change I did was adding a header to the axios API request, but still no luck.
In postman, for parameter named cap, you're sending a .json file. But in your reactjs code, you're doing
formData.append('cap', JSON.parse(stringCap));
JSON.parse will create a javascript object which is not what your backend is expecting. You need to send it as a JSON file.
Not tested, but this might give you the idea.
const json = JSON.stringify(cap);
const blob = new Blob([json], {
type: 'application/json'
});
var formData = new FormData();
formData.append('cap', blob);
formData.append('file', this.state.imageFile)
axios.post('http://localhost:8080/bottlecap/entry', formData, {headers:{'Content-Type':'multipart/form-data'}})
.then(res=>{
console.log(res.data);
}
This is my fetch sample in Vue3, and it works thanks to you. Thanks!
let formData = new FormData();
formData.append('productJsonData', new Blob([JSON.stringify(productJsonObject)], {type: 'application/json'}));
formData.append('file', image); // This image comes from an <v-file-input> TAG
const response = await fetch(
`http://.../addProduct`,
{
headers: { 'Accept': 'application/json' },
method: 'POST',
body: formData
}
);
const responseData = await response.json();
if (!response.ok) {
console.log('REST error: [' + responseData.error + ']')
throw error;
}

Throwing error while downloading file in ASP.NET Core with status code 400

I'm working on download feature. When I run code on localhost, it runs perfectly without any error. But when I uploads same code to server then it returns Failed to load resource: the server responded with a status of 400 (Bad Request) error in console of browser. For requesting and getting response from server, I have used Axios. I'm newbie to ASP.NET Core + ReactJS technology stack and working on APIs for the first time so it's being difficult for me to figuring out root cause of this error.
Here is my code for requesting data from server.
axios({
method: 'POST',
url: '/api/ImageFetch/ImageFetchPoint',
responseType: 'blob',// important
headers: {
'Content-Type': 'application/json'
},
data: filepath
}).then(function(response) {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
}).catch(error => {
console.log("Status:", error.response.status);
console.log("Data:", error.response.data);
});
For getting response as file(any extension) from server, I've used following code.
[HttpPost("PanImageFunction")]
[Route("api/[controller]/[action]")]
public async Task<IActionResult> ImageFetchFunction([FromBody] ImageFetchRequest request)
{
var filePath = request.ImagePath;
var filename = System.IO.Path.GetFileName(filePath);
string path="unknownpath";
try {
if (filename == null)
return Content("filename not present");
path = Path.Combine(
Directory.GetCurrentDirectory(),
"RegistrationImages", filename);
} catch(Exception ex) {
new Logger().write(ex);
}
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = false // false = prompt the user for downloading; true = browser to try to show the file inline
};
Response.Headers.Add("Content-Type", "multipart/form-data");
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.Headers.Add("X-Content-Type-Options", "nosniff");
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
private string GetContentType(string path)
{
var types = GetMimeTypes();
var ext = Path.GetExtension(path).ToLowerInvariant();
return types[ext];
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".txt", "text/plain"},
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"},
{".xls", "application/vnd.ms-excel"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".gif", "image/gif"},
{".csv", "text/csv"}
};
}
Complete code works perfectly on localhost. But when I uploads it on server then it throws 400 bad request error on console of browser as you can see in following image.
I have checked many forums and articles but most of the articles related to ASP.NET core giving solution related to Razor pages and not giving solutions related to ReactJS and Axios.
How can I fix this error?

Unable to Download xlsx on client side using Filesaver.JS in React

I tried the previous solutions on stackoverflow as well as other options including defining responseType as "arraybuffer" and "blob", I'm not able to download xlsx file generated on the client side. The repsonse.data is in the form of byte[].
I see that the file has contents, but when I try to open it, it says - "The file format or file extension is not valid "
UI Snippet:
axios.post('/api/report/generateReport', {}, {
params: {
reportId: this.state.reportId,
lob: this.state.lob
}
}, {responseType: 'arraybuffer'})
.then(function (response) {
var blob = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
FileSaver.saveAs(blob, 'Metrics.xlsx');
})
Backend Snippet
#POST
#Path("/generateReport")
public Response generateReport(#QueryParam("reportId") int reportId, #QueryParam("lob") String lob) {
Response response = null;
byte[] contents = null;
contents = metricsReport.generateReport(lob);
response = Response.status(Response.Status.OK).entity(contents).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Content-Disposition", "attachment; filename=Metrics.xlsx").allow("OPTIONS")
.build();
return response;
}
I think you need to set content-type to application/octet-stream in the response from the server.
Something like(spring boot)-
return ResponseEntity.ok().contentLength(file.contentLength())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header("Content-disposition", "attachment; filename=Metrics.xlsx")
.body(inputStreamResource)

Resources