我已按照 remix-run 的指南进行操作,但无法生成下载文件。
我已经检查了 stackoverflow 的指南: Remix:文件下载 如何从 remix 路径返回纯文本或 css 文件?
以及混音仓库 https://github.com/remix-run/remix/discussions/5533
这是复制问题的示例代码
import { Form } from '@remix-run/react';
export const action = loder () => {
const content = 'some text content...';
console.log('test load')
return new Response(content, {
status: 200,
headers: {
'Content-Type': 'plain/text',
'Content-Disposition': 'attachment; filename="some.txt"',
},
});
}
export const action = async () => {
const content = 'some text content...';
console.log('test action')
return new Response(content, {
status: 200,
headers: {
'Content-Type': 'plain/text',
'Content-Disposition': 'attachment; filename="some.txt"',
},
});
}
export default function Index() {
return (
<>
<Form action="/app/test" method='post'>
<input name="id" value="1" />
<button type="submit">Save</button>
</Form>
<Link to="app/test" reloadDocument>Download</ink>
</>
)
}
这会生成正常的 API 返回而不是 资源路由
注意:这是 Shopify App Remix Boilerplate 源代码的页面
由于您的路由中有 UI 组件,因此这不是资源路由,因此加载器和操作只能返回 JSON。
如果您想返回文件,您应该 POST 到单独的 resource 路线:
// routes/some-ui-route.tsx
import { Form } from '@remix-run/react';
// this is your UI component
export default function Index() {
return (
<>
{/* POST to your resource route */}
<Form action="/upload" method='post'>
<input name="id" value="1" />
<button type="submit">Save</button>
</Form>
<Link to="app/test" reloadDocument>Download</ink>
</>
)
}
// routes/upload.ts
export const action = () => {
const content = 'some text content...';
console.log('test load')
return new Response(content, {
status: 200,
headers: {
'Content-Type': 'plain/text',
'Content-Disposition': 'attachment; filename="some.txt"',
},
});
}