需求: 通过编辑器生成的html被上传到阿里云的服务器,但是这个html 需要嵌入到另外的一个网页里面。
环境
- 前端: react
- 后端: Java
Java代码
@RequestMapping(value = "/getHtml", method = RequestMethod.POST)
@UnNeedAdminId
@Unauthorize
public Object getHtml(@RequestBody Map<String, String> uri) throws Exception {
URL url = new URL(uri.get("url"));
URLConnection URLconnection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
int responseCode = httpConnection.getResponseCode();
String str = "";
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader bufr = new BufferedReader(isr);
String lStr;
while ((lStr = bufr.readLine()) != null) {
str = str + lStr;
}
bufr.close();
} else {
str = "没有内容";
}
return str;
}
react 代码
export default class PHomeLog extends React.Component {
static defaultProps = {};
constructor(props) {
super(props);
this.state = {
siteContent: ""
}
}
componentWillMount() {
let id = this.props.id;
let url = `http://XXXXXXX/${id}/XXX.html`;
Fetch({
host: "XXX",
url: 'api/getHtml',
body: {url},
method: "POST",
}).then((res)=>{
this.setState({
siteContent: res.data
})
})
}
createMarkup = (html) => {
return {__html: html};
};
// 替换返回的html中被转义的字符
escapeChars=(str)=> {
str = str.replace(/&/g, '&');
str = str.replace(/</g, '<');
str = str.replace(/>/g, '>');
str = str.replace(/´/g, '\'');
str = str.replace(/"/g, '"');
str = str.replace(/¦/g, '\\|');
str = str.replace(/'/g, '\'');
return str;
}
render() {
let {siteContent} = this.state;
siteContent = this.escapeChars(siteContent)
return (
<div>
{
siteContent?
<div dangerouslySetInnerHTML={this.createMarkup(siteContent)}></div>:
<div className="pusht">暂无日志……</div>
}
</div>
);
}
}