乐趣区

Spring-MVC-文件流形式下载返回视频文件


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();}

}
退出移动版