一、方式1
存在静态文件,音频或视频文件可存储到项目路径下
(1)文件存储在服务路径 webapp 路径下,如下图所示
(2)浏览器可以直接访问
(3)HTML 内容
<audio id="audio" src="/static-file-server/audio/lie.mp3" controls></audio>
二、方式2
无静态文件,音/视频文件由代码动态生成,或存储于数据库(blob类型字段)
(1)HTML 内容
<audio id="audio" src="/server/audio/loading?id=1" controls></audio>
(2)Java 后台
import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@Controller
@RequestMapping("/audio")
public class AudioController {
@Autowired
AudioServcie audioServcie;
@RequestMapping(value = "/loading", method = RequestMethod.GET)
@ResponseBody
public void loading(HttpServletRequest request, HttpServletResponse response) throws IOException {
long audioId = new Long(request.getParameter("id"));
Audio audio = audioServcie.getByKey(audioId);
if (null == audio || null == audio.getBlob()) {
return;
}
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
response.setContentType("application/octet-stream");//TODO 关键
fis = (FileInputStream) audio.getBlob().getBinaryStream();
bis = new BufferedInputStream(fis);
byte[] b = new byte[bis.available()];
bis.read(b);
os = response.getOutputStream();
if (b.length > 0) {
os.write(b);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != os) {
os.flush();
os.close();
}
if (null != bis) {
bis.close();
}
if (null != fis) {
fis.close();
}
}
}
}