SpringBoot文件下载(Zip & Xml)
1、 Zip
java-controller
@GetMapping(value = "downLoadXmlZip")
@ApiOperation(value = "根据topProtocol获取模板zip", notes = "获取某一个protocol的xml文本")
public void downLoadXmlZip(@NotNull(message = "根据topProtocol获取模板zip") Long topProtocol, HttpServletResponse response){
try {
sfProtocolService.downLoadXmlZip(topProtocol, response);
} catch (Exception e) {
e.printStackTrace();
}
}
java-Service
void downLoadXmlZip(Long topProtocol, HttpServletResponse response) throws IOException;
@Override
public void downLoadXmlZip(Long topProtocol, HttpServletResponse response) throws IOException {
List<SfProtocolEntity> downloadList = sfProtocolService.getParentAndChildListIdName(topProtocol);
List<Path> files = new ArrayList<>();
downloadList.forEach(item -> {
SfFilePathEntity sfFilePathEntity = sfFilePathService.getOne(new LambdaQueryWrapper<SfFilePathEntity>()
.eq(SfFilePathEntity::getProtocolId, item.getId()));
files.add(Paths.get(sfFilePathEntity.getPath()));
});
String fileName = "模板文件.zip";
response.setContentType("application/zip");
FileUtils.setAttachmentResponseHeader(response,fileName);
try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
for (Path file : files) {
try (InputStream inputStream = Files.newInputStream(file)) {
zipOutputStream.putNextEntry(new ZipEntry(file.getFileName().toString()));
StreamUtils.copy(inputStream, zipOutputStream);
zipOutputStream.flush();
}
}
}
}
java-utils
package cn.datax.service.data.metadata.util;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class FileUtils extends org.apache.commons.io.FileUtils
{
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
{
String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(percentEncodedFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(percentEncodedFileName);
response.setHeader("Content-disposition", contentDispositionValue.toString());
}
public static String percentEncode(String s) throws UnsupportedEncodingException
{
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\\+", "%20");
}
}
vue-api
export function downLoadXmlZip(id) {
return request({
url: '/data/metadata/stepForm/downLoadXmlZip?topProtocol=' + id,
method: 'get',
responseType: 'blob',
headers:{ 'Content-Type': 'application/zip'}
})
}
vue-componet
downLoadStepForm(id){
downLoadXmlZip(id).then(response => {
const blob = new Blob([response], { type: 'application/zip' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = '模板文件.zip';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch(error => {
console.error('Error downloading ZIP file:', error);
});
},
result
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/97368952bc954ace9103b2a644f46e4a.png)
2、 Xml
java-controller
@GetMapping("downLoadXml")
@ApiOperation(value = "返回blob", notes = "返回blob")
public void downLoadXml(@NotNull(message = "protocol不能是空") Long protocol, HttpServletResponse response){
try {
sfProtocolService.downLoadXml(protocol, response);
} catch (Exception e) {
e.printStackTrace();
}
}
java-Service
void downLoadXml(Long protocol, HttpServletResponse response) throws UnsupportedEncodingException;
@Override
public void downLoadXml(Long protocol, HttpServletResponse response) throws UnsupportedEncodingException {
SfFilePathEntity sfFilePathEntity = sfFilePathService.getOne(new LambdaQueryWrapper<SfFilePathEntity>()
.eq(SfFilePathEntity::getProtocolId, protocol));
String filePath = sfFilePathEntity.getPath();
Path path = Paths.get(filePath);
String fileName = path.getFileName().toString();
response.setContentType(MediaType.APPLICATION_XML_VALUE);
FileUtils.setAttachmentResponseHeader(response,fileName);
try (InputStream inputStream = Files.newInputStream(new File(filePath).toPath())) {
FileCopyUtils.copy(inputStream, response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
java-utils
package cn.datax.service.data.metadata.util;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class FileUtils extends org.apache.commons.io.FileUtils
{
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
{
String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(percentEncodedFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(percentEncodedFileName);
response.setHeader("Content-disposition", contentDispositionValue.toString());
}
public static String percentEncode(String s) throws UnsupportedEncodingException
{
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\\+", "%20");
}
}
vue-api
export function downLoadXml(id) {
return request({
url: '/data/metadata/stepForm/downLoadXml?protocol=' + id,
method: 'get',
responseType: 'blob',
headers:{ 'Content-Type': 'application/xml'}
})
}
vue-componet
downLoad(row) {
let id = row.id
let name = row.label
downLoadXml(id).then(response => {
const blob = new Blob([response], {type: 'application/xml'});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = `${name}.xml`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
},
initXmlData(id) {
this.previewType = "xml";
downLoadXml(id).then(res => {
const blob = new Blob([res], { type: 'text/plain' });
this.blobToString(blob).then((result) => {
console.log("result::",result);
this.previewResult = result
console.log("this.previewResultthis.previewResult::",this.previewResult)
});
})
},
result
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/cf07b9d6312045f7abe50839e85309a2.png)