首页 > 解决方案 > 从我得到的响应中反序列化数据

问题描述

我正在获取数据序列化,我认为这会导致 POST 请求出现问题,它会成功,但是当我尝试从源代码查看时,pdf 或任何文件会生成错误或空白图像。

如何反序列化数据我在下面的数据中得到什么 在此处输入图像描述

这就是功能

onFileChangeHandler = (e) => {
        this.setState({
          files: e.target.files[0].name
        });
    };

<input type="file" name="Upload" onChange={this.onFileChangeHandler.bind(this)}/>

有了这个 Input 组件。同样在这里,我将这个文件与 API 调用添加到我必须反序列化的源

if(this.state.files !== undefined){
        try {
          sp.web.lists.getByTitle(this.props.listName).items.add({
            Title: item.Title
        }).then(r => {
            // this will add an attachment to the item we just created to push t sharepoint list
            r.item.attachmentFiles.add(this.state.files, "Here is some file content.");
        });

我认为由于序列化数据,我的附件文件显示失败或空白。我搜索了互联网,并认为反序列化会解决这个问题。谁能帮我这个?反序列化上述数据。

标签: javascriptreactjstypescriptsharepointdeserialization

解决方案


这是一个代码演示,用于将 pdffile 添加到 React SPFX Web 部件的列表项附件中:

import * as React from 'react';
import styles from './HelloWorld.module.scss';
import { IHelloWorldProps } from './IHelloWorldProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { sp } from "@pnp/sp/presets/all";

export interface IMyState {
  pdfFile: File
}

export default class HelloWorld extends React.Component<IHelloWorldProps,IMyState> {

  public constructor(props: IHelloWorldProps, state: IMyState) {
    super(props);
    this.state = {
      pdfFile: null
    }
  };
  handleChange(selectorFiles: FileList) {
    this.setState({ pdfFile: selectorFiles[0] });
  }
  Submit() {
    console.log(this);
    if (this.state.pdfFile !== undefined) {
      try {
        sp.web.lists.getByTitle("list1").items.add({
          Title: "New Item"
        }).then(r => {
          // this will add an attachment to the item we just created to push t sharepoint list
          r.item.attachmentFiles.add(this.state.pdfFile.name, this.state.pdfFile).then(result=>{
            console.log(result);
          });
        })
      } catch{

      }
    }
  }
  public render(): React.ReactElement<IHelloWorldProps> {

    return <div><input type="file" onChange={(e) => this.handleChange(e.target.files)} />
    <button onClick={(e) => this.Submit()}>Submit</button></div>

  }
}

在此处输入图像描述


推荐阅读