0

クライアント側で AJAX 投稿を行うときに、パラメーターqueryParamに基づいて .csv ファイルを生成する Java の Spring ライブラリを使用するサーバーがあります。

$.ajax(
{
    url: myUrl,
    type: 'POST',
    contentType: 'application/json',
    data: queryParam,
    success: function(response)
    {
        console.log(response);
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        console.error("error in query()");
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
    }
});

サーバー側のコードは適切なヘッダーを添付し、データを応答ストリームに直接書き込みます (サーバー上でファイルを作成できないため、そのようにする必要があることに注意してください)。

@RequestMapping(value = "/query", method = RequestMethod.POST)
public void exportSearchEvents(HttpServletResponse resp, @RequestBody QueryParams params)
{
    Writer os=null;

    try
    {
        resp.setHeader("Content-Disposition", "attachment; filename=\"searchresults.csv\"");
        resp.addHeader("Content-Type", "application/force-download");
        resp.addHeader("Content-Type", "application/csv");
        resp.addHeader("Content-Type", "application/x-download");

        resp.setContentLength(580);
        resp.addHeader("Pragma", "public");
        resp.addHeader("Expires", "0");
        resp.addHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        os = resp.getWriter();
        createFile(os, params); //writes the .csv data to the response PrintWriter object
        os.flush();
        os.close();
    }
    catch(Exception e)
    {
        logger.info("Error creating .csv file. " + e.getMessage());
        logger.error("Error creating .csv file.", e);
    }

    logger.info("got to here. " + resp.toString());

    if(os==null)
    {
        logger.info("Error creating .csv file: null");
        logger.error("Error creating .csv file: null");
        return;
    }
    return;
}

返されると、結果の文字列が返されます (.csv にあるはずです) が、ダウンロード オプション ボックスがポップアップしません。

また、ファイルのアクセス許可を変更できないため、サーバー上にファイルを作成してブラウザーからリンクすることはできません(つまり、 document.location.href = /server/createdfile.csvなど)。また、さまざまな場所にhrefするさまざまな形式の非表示のiframeも試しましたが、何らかの方法でサーバーにqueryParamを提供する必要があるため、それはできません(間違っている場合は修正してください)。
また、Spring の制限により、単純な POST と GET は機能しません (Spring の問題だと思います)。

$.get(myUrl, queryParam, function(response)
{
    console.log(response);
});

$.post(myUrl, queryParam, function(response)
{
    console.log(response);
});

ください:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

また、私は Flash を避けていることに注意してください。Flash に関する回答はありません。

前もって感謝します。

4

1 に答える 1