2016-10-03 1 views
5

Я использую этот код Java для загрузки файлов из веб-приложения:Spring OutputStream - скачать PPTX с IE

@RequestMapping(value = "/filedownloads/filedownload/{userid}/{projectid}/{documentfileid}/{version}/", method = RequestMethod.GET) 
public void filesDownload(final @PathVariable("userid") String userId, final @PathVariable("projectid") String projectId, 
     final @PathVariable("documentfileid") String documentFileId, final @PathVariable("version") String version, 
     final HttpServletResponse response) throws IOException, BusinessException { 

    ... 

    final String fileName = "filename=" + documentFile.getFileName(); 
    final InputStream is = new FileInputStream(filePath); 
    response.setHeader("Content-Disposition", "inline; " + fileName); 
    IOUtils.copy(is, response.getOutputStream()); 
    response.flushBuffer(); 
} 

если загрузит pptx- файл я получаю следующую IE- страница:

opend pptx in IE

Что я хочу сделать, так это открыть загруженный файл в Powerpoint. Мой вопрос теперь будет, если есть заголовок настройки для того, чтобы открыть этот файл с помощью правильного применения (в данном случае Powerpoint)

ответ

2

Просто попробуйте установить заголовок Content Type правильно, который в случае pptxapplication/vnd.openxmlformats-officedocument.presentationml.presentation, в следующем :

response.setContentType(
    "application/vnd.openxmlformats-officedocument.presentationml.presentation" 
); 
response.setHeader(
    "Content-Disposition", 
    String.format("inline; filename=\"%s\"", documentFile.getFileName()) 
); 
response.setContentLength((int) new File(filePath).length()); 

Here is the list of mime types corresponding to Office 2007 documents.

1

Вот небольшой пример кода из MVC контроллер Spring:

@RequestMapping("/ppt") 
public void downloadPpt(HttpServletRequest request, HttpServletResponse response) throws IOException { 
    Resource resource = new ClassPathResource("Presentation1.pptx"); 

    InputStream resourceInputStream = resource.getInputStream(); 
    response.setHeader("Content-Disposition", "attachment; filename=\"Presentation1.pptx\""); 
    response.setContentLengthLong(resource.contentLength()); 

    byte[] buffer = new byte[1024]; 
    int len; 
    while ((len = resourceInputStream.read(buffer)) != -1) { 
     response.getOutputStream().write(buffer, 0, len); 
    } 

} 

Установив Content-Disposition на номер attachment, вы сообщаете браузеру, чтобы загрузить этот файл в качестве вложения и, указав правильное имя файла с расширением, вы сообщаете операционной системе, чтобы использовать любое приложение, которое пользователь обычно использует для открытия файл этого типа. В этом случае это будет MS Power Point.

Таким образом, вы можете уйти, не зная точно, какую версию Power Point создала файл.

0

Я проверил код в IE-11, его работа прекрасна. Смотрите ниже код т.е.

@RequestMapping(value = "/downloadfile", method = RequestMethod.GET) 
    @ResponseBody 
    public void downloadfile(HttpServletRequest request, HttpServletResponse response) throws Exception { 
     ServletOutputStream servletOutputStream = null; 

     try { 
      response.setContentType("application/octet-stream"); 
      response.setHeader("Content-Disposition", "attachment; filename=downloadppt.pptx"); 

      byte[] ppt = downloadFile(); 

      servletOutputStream = response.getOutputStream(); 
      servletOutputStream.write(ppt); 
     } catch (Exception e) { 
      throw e; 
     } finally { 
      servletOutputStream.flush(); 
      servletOutputStream.close(); 
     } 
    } 

Генерация bytes из сохраненного файла pptx.

public byte[] downloadFile() throws IOException { 
     InputStream inputStream = new FileInputStream(new File("e:/testppt.pptx")); 
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

     // Transfer bytes from source to destination 
     byte[] buf = new byte[1024]; 
     int len; 
     while ((len = inputStream.read(buf)) > 0) { 
      byteArrayOutputStream.write(buf, 0, len); 
     } 

     inputStream.close(); 
     byteArrayOutputStream.close(); 
     return byteArrayOutputStream.toByteArray(); 
    } 

Вот так, вы можете загрузить файл pptx. Код надежды поможет вам, если у вас возникнут какие-либо вопросы или сомнения, мы можем обсудить или любые предложения. Спасибо

 Смежные вопросы

  • Нет связанных вопросов^_^