扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping(value = "json/file")
public class JsonFileController {@GetMapping(value = "download")
public void downLoad(HttpServletResponse response) {response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;fileName=demo.json");
// 制造假数据,模拟JSON数据
Listlist = new ArrayList<>();
list.add(new Person(1L, "张三", 18));
list.add(new Person(2L, "李四", 20));
list.add(new Person(3L, "王五", 26));
ByteArrayInputStream is = null;
OutputStream os = null;
try {// 对象转换为字符串
// String s = JSON.toJSONString(list);
String s = "{\"code\":0,\"data\":\"aaaaaa\",\"msg\":\"成功\"}";
System.out.println(s);
is = new ByteArrayInputStream(s.getBytes());
os = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {os.write(buffer, 0, len);
}
} catch (IOException e) {e.printStackTrace();
} finally {if (os != null) {try {os.close();
} catch (IOException e) {e.printStackTrace();
}
}
if (is != null) {try {is.close();
} catch (IOException e) {e.printStackTrace();
}
}
}
}
}
二、导出文件名详见:fileName=demo.json
response.setHeader("Content-Disposition", "attachment;fileName=demo.json");
在postman中,会直接得到json文件内容
在浏览器上时,会直接得到一个文件
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流