如何在Laravel中返回多个文件

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

How to return multiple file in laravel

问题

以下是您要翻译的内容:

使用的语言:php与laravel以及js与react

我正在尝试从服务器端(laravel)向客户端(react)发送文件响应。

$generatedFiles是一个包含所有要返回的docx文件的数组。

要知道的是:当我只返回一个文件时,它可以正常工作,但我不知道如何返回多个文件。

服务器端:

$generatedFiles[] = public_path() . '/' . $fileName . '.docx'; // 在这里需要返回generatedFiles中的所有文件
return response()->file(这里需要返回generatedFiles中的所有文件);

这是我返回一个文件的方式(有效):

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

这是我在客户端(react)中获取响应的方式:

export const postProject = (datas) => async (dispatch) => {
  console.log(datas);
  dispatch(setPostLoading(true));

  await axios({
    method: 'post',
    url: `${process.env.REACT_APP_API}/api/projects`,
    data: datas,
    responseType: 'blob',
    headers: {
      Accept:
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    },
  }).then((res) => {
    if (!res.data) {
      dispatch(setError(true));
    } else {
      var blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      });
      saveAs(blob, 'test.docx');
    }
  });
  dispatch(setPostLoading(false));
};

我尝试过的方法:

- 尝试实现压缩文件但出现“压缩的zip文件无效”错误:

  foreach ($generatedFiles as $file) {
    $zip->addFile($file, basename($file)); // 将每个生成的docx文件添加到zip中
  }

  $zip->close();

  // 读取zip文件并将其内容作为响应发送
  $fileContents = file_get_contents($zipPath);
  $response = response()->make($fileContents, 200, [
    'Content-Type' => 'application/zip',
    'Content-Disposition' => 'attachment; filename="generated_files.zip"',
  ]);

  // 清理临时文件
  unlink($zipPath);

  return $response;

- 尝试将我的generatedFiles数组作为json返回,并在客户端映射它,但然后我不知道如何处理generatedFiles映射中的元素

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 :

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

This is how i return one file (working)

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

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

export const postProject = (datas) => async (dispatch) => {
  console.log(datas);
  dispatch(setPostLoading(true));

  await axios({
    method: 'post',
    url: `${process.env.REACT_APP_API}/api/projects`,
    data: datas,
    responseType: 'blob',
    headers: {
      Accept:
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    },
  }).then((res) => {
    if (!res.data) {
      dispatch(setError(true));
    } else {
      var blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      });
      saveAs(blob, 'test.docx');
    }
  });
  /* .then(() => {
      dispatch(deleteDocxFile());
    });*/
  dispatch(setPostLoading(false));
};

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
    }

     $zip->close();
    
     // Read the zip file and send its contents as a response
     $fileContents = file_get_contents($zipPath);
     $response = response()->make($fileContents, 200, [
         'Content-Type' => 'application/zip',
         'Content-Disposition' => 'attachment; filename="generated_files.zip"',
     ]);
    
     // Clean up the temporary files
     unlink($zipPath);
    
     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文件。

$zipFileName = 'generated_files.zip';
$zipPath = public_path($zipFileName);
$zip = new ZipArchive();

if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
    // 无法创建ZIP文件
    return response()->json(['error' => '无法创建ZIP文件'], 500);
}

foreach ($generatedFiles as $generatedFile) {
    // 将每个生成的DOCX文件添加到ZIP存档中
    $docxFileName = basename($generatedFile);
    $zip->addFile($generatedFile, $docxFileName);
}

$zip->close();

// 可选:删除单个生成的DOCX文件
foreach ($generatedFiles as $generatedFile) {
    unlink($generatedFile);
}

// 作为响应返回ZIP文件
return response()->download($zipPath)->deleteFileAfterSend(true);

然后在客户端:

export const postProject = (datas) => async (dispatch) => {
  console.log(datas);
  dispatch(setPostLoading(true));

  await axios({
    method: 'post',
    url: `${process.env.REACT_APP_API}/api/projects`,
    data: datas,
    responseType: 'blob',
  }).then((res) => {
    if (!res.data) {
      dispatch(setError(true));
    } else {
      const blob = new Blob([res.data], {
        type: 'application/zip', // 设置ZIP文件的正确内容类型
      });
      saveAs(blob, 'generated_files.zip');
    }
  });

  dispatch(setPostLoading(false));
};
英文:

Resolved :

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

  $zipFileName = 'generated_files.zip';
    $zipPath = public_path($zipFileName);
    $zip = new ZipArchive();

    if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
        // Unable to create the ZIP file
        return response()->json(['error' => 'Failed to create ZIP file'], 500);
    }

    foreach ($generatedFiles as $generatedFile) {
        // Add each generated DOCX file to the ZIP archive
        $docxFileName = basename($generatedFile);
        $zip->addFile($generatedFile, $docxFileName);
    }

    $zip->close();

    // Remove the individual generated DOCX files (optional)
    foreach ($generatedFiles as $generatedFile) {
        unlink($generatedFile);
    }

    // Return the ZIP file as the response
    return response()->download($zipPath)->deleteFileAfterSend(true);µ

and then client side :

 export const postProject = (datas) => async (dispatch) => {
  console.log(datas);
  dispatch(setPostLoading(true));

  await axios({
    method: 'post',
    url: `${process.env.REACT_APP_API}/api/projects`,
    data: datas,
    responseType: 'blob',
  }).then((res) => {
    if (!res.data) {
      dispatch(setError(true));
    } else {
      const blob = new Blob([res.data], {
        type: 'application/zip', // Set the correct content type for the ZIP file
      });
      saveAs(blob, 'generated_files.zip');
    }
  });
  /* .then(() => {
      dispatch(deleteDocxFile());
    });*/
  dispatch(setPostLoading(false));
};

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:

确定