如何在Laravel中返回多个文件

huangapple go评论99阅读模式
英文:

How to return multiple file in laravel

问题

以下是您要翻译的内容:

  1. 使用的语言:phplaravel以及jsreact
  2. 我正在尝试从服务器端(laravel)向客户端(react)发送文件响应。
  3. $generatedFiles是一个包含所有要返回的docx文件的数组。
  4. 要知道的是:当我只返回一个文件时,它可以正常工作,但我不知道如何返回多个文件。
  5. 服务器端:
  6. $generatedFiles[] = public_path() . '/' . $fileName . '.docx'; // 在这里需要返回generatedFiles中的所有文件
  7. return response()->file(这里需要返回generatedFiles中的所有文件);
  8. 这是我返回一个文件的方式(有效):
  9. return response()->file(public_path() . '/' . $fileName . '.docx');
  10. 这是我在客户端(react)中获取响应的方式:
  11. export const postProject = (datas) => async (dispatch) => {
  12. console.log(datas);
  13. dispatch(setPostLoading(true));
  14. await axios({
  15. method: 'post',
  16. url: `${process.env.REACT_APP_API}/api/projects`,
  17. data: datas,
  18. responseType: 'blob',
  19. headers: {
  20. Accept:
  21. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  22. },
  23. }).then((res) => {
  24. if (!res.data) {
  25. dispatch(setError(true));
  26. } else {
  27. var blob = new Blob([res.data], {
  28. type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  29. });
  30. saveAs(blob, 'test.docx');
  31. }
  32. });
  33. dispatch(setPostLoading(false));
  34. };
  35. 我尝试过的方法:
  36. - 尝试实现压缩文件但出现“压缩的zip文件无效”错误:
  37. foreach ($generatedFiles as $file) {
  38. $zip->addFile($file, basename($file)); // 将每个生成的docx文件添加到zip中
  39. }
  40. $zip->close();
  41. // 读取zip文件并将其内容作为响应发送
  42. $fileContents = file_get_contents($zipPath);
  43. $response = response()->make($fileContents, 200, [
  44. 'Content-Type' => 'application/zip',
  45. 'Content-Disposition' => 'attachment; filename="generated_files.zip"',
  46. ]);
  47. // 清理临时文件
  48. unlink($zipPath);
  49. return $response;
  50. - 尝试将我的generatedFiles数组作为json返回,并在客户端映射它,但然后我不知道如何处理generatedFiles映射中的元素
  51. return response()->json($generatedFiles);
英文:

Language used : php with laravel and js with react

I am trying to send a response as file from server side (laravel) to client side (react).

$generatedFiles is an array who contain all docx to return.

To know : It's working when I return only one file, but I don't know how to return multiple

SERVER SIDE :

  1. $generatedFiles[] = public_path() . '/' . $fileName . '.docx'; //
  2. return response()->file(Here need to return all file in generatedFiles);

This is how i return one file (working)

  1. return response()->file(public_path() . '/' . $fileName . '.docx');

This is how I get the response in my client (react) side

  1. export const postProject = (datas) => async (dispatch) => {
  2. console.log(datas);
  3. dispatch(setPostLoading(true));
  4. await axios({
  5. method: 'post',
  6. url: `${process.env.REACT_APP_API}/api/projects`,
  7. data: datas,
  8. responseType: 'blob',
  9. headers: {
  10. Accept:
  11. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  12. },
  13. }).then((res) => {
  14. if (!res.data) {
  15. dispatch(setError(true));
  16. } else {
  17. var blob = new Blob([res.data], {
  18. type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  19. });
  20. saveAs(blob, 'test.docx');
  21. }
  22. });
  23. /* .then(() => {
  24. dispatch(deleteDocxFile());
  25. });*/
  26. dispatch(setPostLoading(false));
  27. };

What I have tried :

  • tried to implement zip but got "The compressed zip folder is invalid"

    foreach ($generatedFiles as $file) {
    $zip->addFile($file, basename($file)); // Add each generated docx file to the zip
    }

    1. $zip->close();
    2. // Read the zip file and send its contents as a response
    3. $fileContents = file_get_contents($zipPath);
    4. $response = response()->make($fileContents, 200, [
    5. 'Content-Type' => 'application/zip',
    6. 'Content-Disposition' => 'attachment; filename="generated_files.zip"',
    7. ]);
    8. // Clean up the temporary files
    9. unlink($zipPath);
    10. return $response;
  • tried to return my generatedFiles array as json and map through it in client side but then I don't know what to do with the element from generatedFiles map

return response()->json($generatedFiles);

答案1

得分: 1

已解决:

我使用了Laravel中的zip功能来将所有文件打包成一个zip文件。

  1. $zipFileName = 'generated_files.zip';
  2. $zipPath = public_path($zipFileName);
  3. $zip = new ZipArchive();
  4. if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
  5. // 无法创建ZIP文件
  6. return response()->json(['error' => '无法创建ZIP文件'], 500);
  7. }
  8. foreach ($generatedFiles as $generatedFile) {
  9. // 将每个生成的DOCX文件添加到ZIP存档中
  10. $docxFileName = basename($generatedFile);
  11. $zip->addFile($generatedFile, $docxFileName);
  12. }
  13. $zip->close();
  14. // 可选:删除单个生成的DOCX文件
  15. foreach ($generatedFiles as $generatedFile) {
  16. unlink($generatedFile);
  17. }
  18. // 作为响应返回ZIP文件
  19. return response()->download($zipPath)->deleteFileAfterSend(true);

然后在客户端:

  1. export const postProject = (datas) => async (dispatch) => {
  2. console.log(datas);
  3. dispatch(setPostLoading(true));
  4. await axios({
  5. method: 'post',
  6. url: `${process.env.REACT_APP_API}/api/projects`,
  7. data: datas,
  8. responseType: 'blob',
  9. }).then((res) => {
  10. if (!res.data) {
  11. dispatch(setError(true));
  12. } else {
  13. const blob = new Blob([res.data], {
  14. type: 'application/zip', // 设置ZIP文件的正确内容类型
  15. });
  16. saveAs(blob, 'generated_files.zip');
  17. }
  18. });
  19. dispatch(setPostLoading(false));
  20. };
英文:

Resolved :

I have used zip from laravel to pass all my files in a zip.

  1. $zipFileName = 'generated_files.zip';
  2. $zipPath = public_path($zipFileName);
  3. $zip = new ZipArchive();
  4. if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
  5. // Unable to create the ZIP file
  6. return response()->json(['error' => 'Failed to create ZIP file'], 500);
  7. }
  8. foreach ($generatedFiles as $generatedFile) {
  9. // Add each generated DOCX file to the ZIP archive
  10. $docxFileName = basename($generatedFile);
  11. $zip->addFile($generatedFile, $docxFileName);
  12. }
  13. $zip->close();
  14. // Remove the individual generated DOCX files (optional)
  15. foreach ($generatedFiles as $generatedFile) {
  16. unlink($generatedFile);
  17. }
  18. // Return the ZIP file as the response
  19. return response()->download($zipPath)->deleteFileAfterSend(true);µ

and then client side :

  1. export const postProject = (datas) => async (dispatch) => {
  2. console.log(datas);
  3. dispatch(setPostLoading(true));
  4. await axios({
  5. method: 'post',
  6. url: `${process.env.REACT_APP_API}/api/projects`,
  7. data: datas,
  8. responseType: 'blob',
  9. }).then((res) => {
  10. if (!res.data) {
  11. dispatch(setError(true));
  12. } else {
  13. const blob = new Blob([res.data], {
  14. type: 'application/zip', // Set the correct content type for the ZIP file
  15. });
  16. saveAs(blob, 'generated_files.zip');
  17. }
  18. });
  19. /* .then(() => {
  20. dispatch(deleteDocxFile());
  21. });*/
  22. dispatch(setPostLoading(false));
  23. };

huangapple
  • 本文由 发表于 2023年7月20日 18:30:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定