JAVA-下载文件 文件下载到浏览器默认位置 输入string转InputStream以文件形式下载 string\InputStream\OutputStream互转


本博客是基于JAVA项目,将输入string转InputStream ,然后将文件下载至浏览器默认位置。 还涉及inputstream转string,string写入outputStream,output写入string;还有常用Content-type格式

1、string转InputStream

第一部分是string转InputStream
也罗列了有inputstream转string,string写入outputStream,output写入string备用吧~

//string转inputstream
String inputStr = "testXXX";
InputStream inputStream = new ByteArrayInputStream(inputStr.getBytes());

//inputstream转string
ByteArrayOutputStream outs = new ByteArrayOutputStream();
int i;
while((i = i.read() != -)){
    
    
    outs.write(i);
}
String str = outs.toString();

//string写入outputStream
OutputStream os = System.out;
os.write(string.getByte());

//output写入string
ByteArrayOutputStream outs = new ByteArrayOutputStrea();
String str = outs.toString();

2、下载文件

需要在controller接口入参直接传HttpServletResponse response,把响应的数据设置到HttpServletResponse 对象中,
然后 Tomcat 就会把这个 HttpServletResponse 对象按照 HTTP 协议的格式, 转成一个字符串, 并通过Socket 写回给浏览器

输入设置文件名称(fileName)和需要下载的文件类型(contentType),contentType可看下部分详解

inputStream是要下载的文件流,无论是网络文件还是存储在云服务-COS静态存储服务中的文件,都可以转化成InputStream的形式

	public void downloadFile(HttpServletResponse response, InputStream inputStream, String fileName, String contentType) {
    
    
        try (BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
    
    
            //通知浏览器以附件形式下载
            response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
            //文件输出格式
            response.setContentType(contentType);
            byte[] input = new byte[1024];
            int len;
            while ((len = inputStream.read(input)) != -1) {
    
    
                out.write(car, 0, len);
            }
        } catch (IOException e) {
    
    
            log.error("Method:downloadFile,ErrorMsg:{}", e.getMessage());
        }
    }

controller接口

 @GetMapping("/download")
 public void download(HttpServletResponse response) {
    
    
         return this.downloadFile(response);
    }

Content-type

text/plain 纯文本格式
text/javascript JSON格式
text/plain HTML格式
text/xml XML格式

image/gif GIF图片格式
image/jpeg JPEG图片格式
image/png PNG图片格式
image/tiff TIFF格式
image/x-dcxi DCX格式
image/x-pcx PCX格式

application/xml XML数据格式
application/json JSON数据格式
application/pdf PDF格式
application/rtf RTF格式
application/msword Word文档格式
application/vnd.ms-excel Excel文档格式
application/vnd.ms-powerpoint Powerpoint文档格式
application/vnd.visio Visio文档格式
application/octet-stream 二进制流数据

猜你喜欢

转载自blog.csdn.net/weixin_44436677/article/details/128010128