react backend and frontend download file
import { View as ViewFile} from '@/api/SafetyRule';
const Handler_DownLoadFile = (Id:number,IsEnglish:boolean)=>{ sfParam.Id=Id; sfParam.IsEnglish=IsEnglish; setSFParam(sfParam); console.log(JSON.stringify(sfParam)) ViewFile(sfParam as SafetyRuleParamPO) .then((res)=>{ if (res.StatusCode == 200 && res.Data){ if(res.Data.FileContent!=undefined){ const blob = UtilFile.ConvertBase64UrlToBlob(res.Data.FileContent); const url = window.URL.createObjectURL( new Blob([blob],{type:'application/pdf'}) ); const link = document.createElement('a'); link.href = url; link.setAttribute( 'download', "FileName.pdf", ); // Append to html link element page document.body.appendChild(link); // Start download link.click(); window.URL.revokeObjectURL(url); } }else{ alert("error") } }) }
export function ConvertBase64UrlToBlob(base64Data):Blob { const byteCharacters = atob(base64Data); const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); const blob = new Blob([byteArray], {type: 'application/pdf'}); return blob; }
import Request from '@/api/request'; import ApiResponsePO from "@/model/ResponseDTO/ApiResponseDTO"; import SafetyRuleViewPO from '@/model/PO/SafetyRuleViewPO' const http = new Request(); export const urlViewFile = '/api/SafetyRule/View' export const View = (params: SafetyRuleParamPO): Promise<ApiResponsePO<SafetyRuleViewPO>> => { return http.get<object, ApiResponsePO<SafetyRuleViewPO>>(urlViewFile,params); }
recommen a :base64 to blob Code Example (codegrepper.com)
backend
public SafetyRuleViewVO ReadFile(int Id,bool IsEnglish) { var safetyVO = GetById(Id); var viewVO = new SafetyRuleViewVO(); if (safetyVO != null) { string filePath = IsEnglish ? safetyVO.EnglishVersionFileSharePointPath : safetyVO.ChineseVersionFileSharePointPath; byte[] fileContent = File.ReadAllBytes(filePath); viewVO = new SafetyRuleViewVO { FileContent = fileContent }; } return viewVO; }
public class SafetyRuleViewVO { public byte[] FileContent { get; set; } }