我想实现一个CSV导出从Shopware 6管理。我有一个按钮,想打开一个新窗口,得到一个CSV文件。
我实现了一个控制器:
/**
* @Route(
* "/api/winkelwagen/export/csv/{id}",
* methods={"GET"},
* defaults={"auth_required"=true, "_routeScope"={"api"}}
* )
*/
public function export(string $id, Context $context, Request $request): Response
{
/** @var PromotionEntity $promo */
$response->setContent('csv file');
return $response;
}但是要调用这个控制器,您需要登录,这完全是有意义的。
我的管理按钮当前打开一个新窗口并打开页面:
window.open('http://www.fabian-blechschmidt.de', '_blank');当然,它不适用于api url,因为您需要进行身份验证。
因此,我的问题是:如何实现此身份验证并在后端获取CSV文件?:-)
也许我的方法完全失败了--很高兴得到一个更好的主意!
发布于 2022-08-26 13:01:55
为了扩展dneustadt的回答,下面的代码片段实际上也下载了csv作为一个文件,方法是将数据加载到数据url中并实际单击它。
const initContainer = Shopware.Application.getContainer('init');
initContainer.httpClient.get(
`winkelwagen/export/csv/${id}`,
{
headers: {
Accept: 'application/vnd.api+json',
Authorization: `Bearer ${Shopware.Service('loginService').getToken()}`,
'Content-Type': 'application/json',
},
},
).then((response) => {
if (response.data) {
const filename = response.headers['content-disposition'].split('filename=')[1];
const link = document.createElement('a');
link.href = URL.createObjectURL(response.data);
link.download = filename;
link.dispatchEvent(new MouseEvent('click'));
link.parentNode.removeChild(link);
}
});发布于 2022-08-26 12:34:57
您可以使用内置的http客户端并设置用于身份验证的承载令牌:
const initContainer = Shopware.Application.getContainer('init');
initContainer.httpClient.get(
`winkelwagen/export/csv/${id}`,
{
headers: {
Accept: 'application/vnd.api+json',
Authorization: `Bearer ${Shopware.Service('loginService').getToken()}`,
'Content-Type': 'application/json',
},
},
);根据您的需要更改标题。
发布于 2022-08-26 18:05:40
是个很好的开始!但是Rune Laenen的回答是金的!
但我认为,由于我不返回JSON,而是返回CSV文件,我需要更改一些东西。
"作为前缀和后缀--我们删除了这些。URL.createObjectURL所需要的-没问题,我们只是创建一个。 if (response.data) {
let filename = response.headers['content-disposition'].split('filename=')[1];
filename = filename.substring(1, filename.length - 1);
const link = document.createElement('a');
link.href = URL.createObjectURL(new Blob([response.data], {type: response.headers['content-type']}));
link.download = filename;
link.dispatchEvent(new MouseEvent('click'));
try {
link.parentNode.removeChild(link);
} catch (e) {
// do nothing
}
}https://stackoverflow.com/questions/73500519
复制相似问题