import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; 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.RestController; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; /** * 文件流形式下載視頻 * @author Front Ng * @date 2019-05-23 09:25 **/ @Controller @RequestMapping(value = "/download") @Api(value = "下載", tags = "下載") public class DownloadController { @ApiOperation(value = "下載視頻") @RequestMapping(method = RequestMethod.GET) public void download(HttpServletResponse response) throws IOException { File file = new File("/Users/front/Downloads/123.mp4"); FileInputStream inputStream = new FileInputStream(file); byte[] data = new byte[(int) file.length()]; int length = inputStream.read(data); inputStream.close(); String fileName = URLEncoder.encode("文件流形式視頻.mp4", "UTF-8"); response.setContentType("application/octet-stream;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); response.addHeader("Content-Length", "" + data.length); OutputStream stream = response.getOutputStream(); stream.write(data); stream.flush(); stream.close(); } }