后端输出xml流

  • Post author:
  • Post category:其他



import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * date: 2021/08/28
 *
 */
@Controller
@Slf4j
@RequestMapping("/xml")
public class XmlController {

    @GetMapping("/xml}")
    public void xml(HttpServletResponse response) throws Exception {
        String file = "xxx.xml";
        try {
            //第一种方式,用文件形式
//            FileInputStream inputStream = new FileInputStream(file);
//            byte[] data = new byte[inputStream.available()];
//            inputStream.read(data);

            //第二种方式,直接字符串转二进制
            String xml = "xxx";
            byte[] data = xml.getBytes(StandardCharsets.UTF_8);
            InputStream inputStream = new ByteArrayInputStream(data);

            String diskfilename = UUID.randomUUID() +  ".xml";
            response.setContentType("application/xml");
            //设置Content-Disposition,浏览器会默认下载
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"");
            System.out.println("data.length " + data.length);
            response.setContentLength(data.length);
            response.setHeader("Content-Range", "" + Integer.valueOf(data.length - 1));
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Etag", "W/\"9767057-1323779115364\"");
            OutputStream os = response.getOutputStream();

            os.write(data);
            //先声明的流后关掉!
            os.flush();
            os.close();
            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

}



版权声明:本文为u013252072原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。