从webservice返回文件路径,并在新窗口中打开它

本文关键字:在新窗口中打开 路径 webservice 返回 文件 | 更新日期: 2023-09-27 18:05:30

我只是想将文件路径返回到新创建的PDF并在新窗中打开它。

当我运行这段代码时,我打开一个404窗口并转到/null页面。我假设这意味着我从CreateLabelPdf c#代码返回一个空值。

有人知道为什么我被返回null以及如何修复它吗?

Javascript

function createLabelPdf(sampleIds, line1, line2, line3, loginMatrix, labelStart) {
    var labelInfo = new Object();
    labelInfo.sampleIds = sampleIds;
    labelInfo.line1 = line1;
    labelInfo.line2 = line2;
    labelInfo.line3 = line3;
    labelInfo.labelType = loginMatrix;
    labelInfo.startingLabelPosition = labelStart;

    $.ajax({
        type: "POST",
        url: "DesktopModules/DataManagement/TestService.svc/CreateLabelPdf",
        data: JSON.stringify(labelInfo),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
           window.open(data.d);
        }   
    });
}
c#服务

[OperationContract]
public string CreateLabelPdf(List<string> sampleIds, string line1, string line2, string line3, string labelType, int startingLabelPosition)
{
    List<LabelContent> labels = new List<LabelContent>();

    foreach (var sample in sampleIds)
    {
        LabelContent labelContent = new LabelContent();
        labelContent.Line1 = line1;
        labelContent.Line2 = line2;
        labelContent.Line3 = line3;
        labelContent.LabelId = sample;
        labels.Add(labelContent);
    }
    Creator creator = new Creator
    {
        IncludeLabelBorders = false
    };

    string path = HttpContext.Current.Server.MapPath(@"~'DesktopModules'DataManagement'Pdf'" + 0 + ".pdf");
    creator.PrintLabels(labels, new Avery5160(), path, startingLabelPosition);
    return path;
}

从webservice返回文件路径,并在新窗口中打开它

我终于想通了。我调试了代码,发现错误在这一行:

string path = HttpContext.Current.Server.MapPath(@"~'DesktopModules'DataManagement'Pdf'" + 0 + ".pdf");

它得到一个空引用错误,所以我把代码改为:

string path = System.Web.Hosting.HostingEnvironment.MapPath(@"~'DesktopModules'DataManagement'Pdf'" + 0 + ".pdf");

这是可行的,但随后我需要将相对字符串返回给浏览器,而不是物理路径,所以我输入:

string relativePath = @"'DesktopModules'DataManagement'Pdf'0.pdf";
return relativePath;

结束代码如下:

string path = System.Web.Hosting.HostingEnvironment.MapPath(@"~'DesktopModules'DataManagement'Pdf'" + 0 + ".pdf");
creator.PrintLabels(labels, new Avery5160(), path, startingLabelPosition);
string relativePath = @"'DesktopModules'DataManagement'Pdf'0.pdf";
return relativePath;