从宁静的Web服务下载pdf

时间:2019-07-19 07:01:35

标签: java rest pdf download

我正在编写一个休息服务,当用户在用户计算机上访问该服务时,它将下载pdf。下面是我的控制器类的代码。

当我尝试在浏览器中访问以下URL时,它正在下载.JSON文件而不是PDF文件。

  

URL:-http://localhost:8080/test-service/downloadPDF?userId=abcd&requestingLocation=6&orderId=06006030

我尝试使用以下网站中提到的相同代码。似乎直接的代码,但不确定为什么它不起作用。 http://www.java2novice.com/restful-web-services/jax-rs-download-file/ https://www.javatpoint.com/jax-rs-file-download-example

下面是控制器中的方法。

    @GET
    @RequestMapping(value = "/downloadPDF")
    @Produces("application/pdf")
    public @ResponseBody Response downloadDocument(@RequestParam("userId") String userId,@RequestParam("requestingLocation") String requestinglocation,@RequestParam("orderId") String orderId) {
            String path = "C:\\opt\\autobol\\logs\\autobol\\test2.pdf";
        File file = new File(path);  
            ResponseBuilder response = Response.ok((Object) file);  
            response.header("Content-Disposition","attachment; filename=\"javatpoint_pdf.pdf\"");  
            return response.build(); 

        }

它应该下载pdf文件

下面是下载文件的内容(文件名downloadPDF.json):

{  
   "entity":"C:\\opt\\autobol\\logs\\autobol\\test2.pdf",
   "status":200,
   "metadata":{  
      "Content-Disposition":[  
         "attachment; filename=\"javatpoint_pdf.pdf\""
      ]
   },
   "annotations":null,
   "entityClass":"java.io.File",
   "genericType":null,
   "length":-1,
   "language":null,
   "location":null,
   "lastModified":null,
   "date":null,
   "closed":false,
   "cookies":{  

   },
   "statusInfo":"OK",
   "stringHeaders":{  
      "Content-Disposition":[  
         "attachment; filename=\"javatpoint_pdf.pdf\""
      ]
   },
   "links":[  

   ],
   "entityTag":null,
   "allowedMethods":[  

   ],
   "mediaType":null,
   "headers":{  
      "Content-Disposition":[  
         "attachment; filename=\"javatpoint_pdf.pdf\""
      ]
   }
}

在downloadPDF.json文件中

3 个答案:

答案 0 :(得分:0)

尝试一下

            HttpResponse response = HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(strPath));
            response.TransmitFile(strPath); //File
            response.Flush();
            response.End();
            Response.ContentType = ContentType;
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(strPath));
            Response.WriteFile(strPath);
            Response.End();

答案 1 :(得分:0)

这是一个春季靴子的例子。 您可以参考此示例https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-first-application.html,并将下面的类附加到项目中

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;
import java.io.File;
import java.nio.file.Files;
@Controller
public class DemoController {

    @RequestMapping(value="/getpdf", method=RequestMethod.GET)
    public ResponseEntity<byte[]> getPDF() {
        File file = new File("sample.pdf"); // change to relative path
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        String filename = "output.pdf";
        headers.setContentDispositionFormData(filename, filename);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = null;
        try {
            response = new org.springframework.http.ResponseEntity<>(Files.readAllBytes(file.toPath()), headers, org.springframework.http.HttpStatus.OK);
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}

答案 2 :(得分:0)

使用Spring RestController尝试一下

@PostMapping(value = "/slip", headers = "Accept=application/json",
            produces = "application/pdf")
    public ResponseEntity<Resource> generateSalarySlip(HttpServletRequest request,
                                                       @RequestBody   Locale locale) {
...
...
File file = new File(fileName);
            HttpHeaders header = new HttpHeaders();
            header.setContentType(MediaType.parseMediaType("application/pdf"));

            header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=salaryslip.pdf");
            header.add("Cache-Control", "no-cache, no-store, must-revalidate");
            header.add("Pragma", "no-cache");
            header.add("Expires", "0");
         
InputStream targetStream = new FileInputStream(file);
        Resource resource = new InputStreamResource(targetStream)
            return ResponseEntity.ok()
                    .headers(header)
                    .contentLength(file.length())
                                    .contentType(MediaType.parseMediaType("application/pdf"))
                    .body(resource);

}