fetch
下载
javascript
封装函数
export const fetchBlobResponse = ({
url,
data,
options,
fileName,
autoDownLoad,
}: {
url: string;
data?: any;
options: RequestInit;
fileName?: string;
autoDownLoad?: boolean;
}): Promise<Blob | void | unknown> => {
let finUrl: string = url;
let finOptions: RequestInit = options;
const { method } = options;
if (method && method.toLowerCase() === 'get') {
const locationSearch = data && queryString.stringify(data);
finUrl = locationSearch ? `${url}?${locationSearch}` : url;
}
if (method && (method.toLowerCase() === 'post' || method.toLowerCase() === 'delete')) {
finOptions = {
...options,
body: JSON.stringify(data),
};
}
return fetch(finUrl, {
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
Language: i18n.language,
...getAuthorization(),
},
...finOptions,
})
.then((res) => blobResponseHandle(res, autoDownLoad as boolean, fileName as string))
.catch((ex) => Promise.reject(ex));
};
下载函数
// blob请求处理函数
async function blobResponseHandle(response: Response, autoDownLoad: boolean, fileName: string) {
return Promise.resolve(response)
.then((res) => resposneStateHandler(res))
.then(async (res) => {
const Return = () => {
try {
if (autoDownLoad) {
res
?.clone?.()
?.blob()
.then((blob) => {
const contentDispositionHeader = res?.headers.get('Content-Disposition') || '';
const match = contentDispositionHeader.match(/filename=["']?([^"']+)["']?/);
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = decodeURIComponent(match ? match[1] : fileName || 'defaultName_file');
a.click();
window.URL.revokeObjectURL(url);
});
}
} catch (error) {}
return res?.clone?.()?.blob();
};
try {
const resJson = await res?.clone()?.json();
if (is.Object(resJson) && (resJson.msg || resJson.message)) {
notification.warning({ message: resJson.msg || resJson.message });
return Promise.reject(resJson)
} else return Return()
} catch (error) {
return Return();
}
});
}上传
javascript
const updateImg = document.querySelector<HTMLInputElement>("#updateImg")!;
updateImg.addEventListener('change',(e:any)=>{
const formData = new FormData();
//参数
formData.append('File',e.target.files[0]);
fetch('https://api.com/UploadImgFile', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.error('Error:', error);
});
})axios
下载
javascript
async function downLoad(name:string) {
axios({
url: `http://8.130.113.197:8080/api/file/download/${name}`,
method: 'get',
responseType: 'blob', // important
headers:{'Authorization':localStorage.getItem('token')}
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download',name); // or any other extension
document.body.appendChild(link);
link.click();
});
}下载
javascript
async function down(name:string) {
await axios({
method:'get',//请求方式
url: `http://8.130.113.197:8080/api/file/download/${name}`,
responseType:'blob',//文件流将会被转成
headers:{'Authorization':localStorage.getItem('token')}
}).then(res => {
console.log(res);
const blob = new Blob([res.data]);//处理文档流
const fileName = name;
const down = document.createElement('a');
down.download = fileName;
down.style.display = 'none';//隐藏,没必要展示出来
down.href = URL.createObjectURL(blob);
document.body.appendChild(down);
down.click();
URL.revokeObjectURL(down.href); // 释放URL 对象
document.body.removeChild(down);//下载完成移除
})
}