當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring MVC 特性实现文件下载
生活随笔
收集整理的這篇文章主要介紹了
Spring MVC 特性实现文件下载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼
import java.io.File; import javax.servlet.http.HttpSession; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam;import com.srieservice.dell.ApplicationProperties;@Controller @RequestMapping("/app/download") public class DownloadController {private Logger log = LoggerFactory.getLogger(this.getClass());@Autowiredprivate ApplicationProperties appProperties;@RequestMapping(path= {"", "index"}, method=RequestMethod.GET)public ResponseEntity<byte[]> index(HttpSession session, @RequestParam("filename")String filename) {// 檢查一下是否有下載權限?// 組合文件File downloadFile = new File(this.appProperties.getDocumentFolder(), filename);if (downloadFile.exists()){log.debug("download file : {}", downloadFile.getAbsoluteFile());} else {throw new RuntimeException("文件不存在!");}// 組合 Header,確定 ContentType 和文件名HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", filename); // 構造 ResponseEntityreturn new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(downloadFile), headers, HttpStatus.CREATED);} }總結
以上是生活随笔為你收集整理的Spring MVC 特性实现文件下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 赵明称荣耀坚持全球化 每年拿出营收的10
- 下一篇: gradle idea java ssm