需求: 通過編輯器產生的html被上傳到阿里雲的伺服器,但是這個html 需要嵌入到另外的一個網頁裡面。 環境 前端: react 後端: Java Java代碼
@RequestMapping(value = "/getHtml", method = RequestMethod.POST)@UnNeedAdminId@Unauthorizepublic 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> ); }}