上传下载
图片
Canvas 转图片系列
function getBase64Image(chart) {
return chart.getDataURL();
}
function dataURItoBlob(dataURI) {
const byteString = atob(dataURI.split(',')[1]);
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
} return new Blob([ab], { type: 'image/png' });
}
chart.on('finished', () => {
// 操作
})
直接另存为图片
function downloadImage() {
const link = document.createElement('a');
link.setAttribute('download', 'MintyPaper.png');
link.setAttribute('href', getBase64Image(chart).replace("image/png", "image/octet-stream"));
link.click();
}
const formData = new FormData();
formData.append('image1', dataURItoBlob(getBase64Image(chart)), 'image1.png');
fetch('http://localhost:8080/ZTEMAS/riskevaluation.do?method=exportAssessmentDoc', {
method: 'POST',
body: formData,
});
获取返回的二进制流并唤起下载
fetch('...').then(response => response.blob())
.then(blob => URL.createObjectURL(blob))
.then(url => {
// window.open(url, '_blank');
// URL.revokeObjectURL(url); // 这样唤起下载时会缺少文件名
Object.assign(document.createElement('a'), {
href: url,
download: 'final.docx',
}).click();
});})
后端
获取图片
@PostMapping(params = "method=exportAssessmentDoc")
public void exportAssessmentDoc(HttpServletRequest request, HttpServletResponse response,
@RequestParam("image1") MultipartFile image1
) throws IOException {
String contentType = image1.getContentType();
// byte array to base64
String base64String = Base64.getEncoder().encodeToString(image1.getBytes());
// base64 to byte array
byte[] imageBytes = Base64.getDecoder().decode(base64String);
}
通过 url 获取图片
URL url = new URL("https://img-home.csdnimg.cn/images/20201124032511.png");
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(conn.getInputStream(), baos);
String base64url = Base64.getEncoder().encodeToString(baos.toByteArray());
for (int i = 0; i < sceneNameList.size(); i++) {
scenePicList.add(base64url);
}
通过 filepath 获取图片
File file = new File(CommonUtil.getAttachmentServerPath(request) + workScenario.getUrl());
if (file.exists()) {
scenePicList.add(Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(file)));
} else {
scenePicList.add("");
}
唤起下载
// 下载图片
// Set response headers
response.setContentType(contentType);
response.setContentLength(imageBytes.length);
response.setHeader("Content-Disposition", "attachment; filename=image.png");
// 如果是下载其他附件
String title = "test.doc";
response.reset();
response.setContentType("application/octet-stream;charset=UTF-8");// 文件类型contenttype
response.setHeader("Content-Disposition",
"attachment; filename=\"" + new String(title.getBytes("GBK"), "ISO8859_1") + "\"");
// Write the byte array to the response output stream
response.getOutputStream().write(imageBytes);
response.getOutputStream().flush();