想在浏览器里直接GET目标URL,然后就把PDF在浏览器里预览出来(不用前端插件的前提下),就像这样:
http://docs.spring.io/spring/...
后端代码:
@RequestMapping(value = "/showPDF", method = RequestMethod.GET)
public ResponseEntity<byte[]> pdfDownload(
HttpServletRequest httpServletRequest
) throws IOException
{
String path = XXX省略。。。
File file = new File(path);
HttpHeaders httpHeaders = new HttpHeaders();
String fileName = file.getName();
httpHeaders.setContentDispositionFormData("attachment", java.net.URLEncoder.encode(fileName,"UTF-8"));
httpHeaders.setContentType(MediaType.parseMediaType("application/pdf"));
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
httpHeaders,
HttpStatus.CREATED);
}
然后想在前端直接GET这个URL地址:
http://localhost:8080/FileUpDown/showPDF
但是却成了下载文件而不是预览了。。。
这是chrome的输出:
**Response Headers**
*view source
Content-Disposition:form-data; name="attachment"; filename="1472111731322JavaScript%E6%9D%83%E5%A8%81%E6%8C%87%E5%8D%97.pdf"
Content-Length:21962427
Content-Type:application/octet-stream;charset=UTF-8
Date:Thu, 25 Aug 2016 08:32:56 GMT
Server:Apache-Coyote/1.1*
Conrent-Type明显不对,请问该如何解决?
PHP中文网2017-04-18 09:54:15
Thank you for your answers, this is my solution.
1. Create an uploadFiles folder under the web path.
2. Mapping PDF files in springMVC is like mapping static files.
<mvc:resources mapping="/pdf/**" location="/uploadFiles/"/>
3. Write a controller to return the URL path of the PDF.
@Controller
@CrossOrigin(origins = "*")
public class PDFController {
@ResponseBody
@RequestMapping(value = "/pdf", method = RequestMethod.GET)
public String pdfDownload() throws IOException
{
String retString = null;
String dir = XXXX文件在服务器中路径。
String path = httpServletRequest.getRequestURL() + dir.substring(dir.lastIndexOf('\'));
retString = path.replaceAll("\\","/");
Map<String,Object >map = new HashMap<>();
map.put("code",0);
map.put("pdf",retString);
return JSON.toJSONString(map);
}
}
4, the returned JSON data.
{"code":0,"pdf":"http://127.0.0.1:8080/pdf/1472128890165sample.pdf"}
5. Open the pdf URL directly in the browser to preview the PDF.
PHP中文网2017-04-18 09:54:15
Directly place the pdf file in a static directory on the server, redirect the address to the file path, and the browser will automatically open the preview; you can refer to the browser and directly enter the full path of the next pdf file on the local disk to try and browse The browser also automatically opens the preview
高洛峰2017-04-18 09:54:15
Just like accessing static files, how do you put your js files and how do you put your pdf.
天蓬老师2017-04-18 09:54:15
Go to the response section. There is something in front of the response, which should lead to the preview
伊谢尔伦2017-04-18 09:54:15
Try changing the RequestMapping line to:
@RequestMapping(value = "/showPDF", method = RequestMethod.GET, produces = MediaType.APPLICATION_PDF_VALUE)