0

This issue is related to a No Javascript Framework SPFx webpart with RestAPI on Sharepoint 2019. The webpart contains a 'text' and 'file upload' fields. The aim is to fill in the text field, select a file to upload and click "Submit" button. The text field column value is unique and need to map to the uploaded file, so an Attachment to the List item was considered easier but the process is failing.

Please help with the method shown below:

<input type="text" id="idTitle" name="Title" placeholder="Serial Number."><br />  
<input id="upload" type="file"/><br />  
<button class="create-Button ${styles.button}" ><span class="${styles.label}">Submit Order</span></button>

SaveItem(): void { 
var newfileName = document.getElementById('upload').files[0].name;

const body: string = JSON.stringify({ 
        'Title': document.getElementById('idTitle')["value"],  
      });  
  this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items`, 
      SPHttpClient.configurations.v1, 
      { 
  headers: { 
  'Accept': 'application/json;odata=nometadata', 
  'Content-type': 'application/json;odata=nometadata', 
  'odata-version': ''
        },
 this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.Listname}')/items({item_id})/AttachmentFiles/ add(FileName='{newfileName}')`, 
      SPHttpClient.configurations.v1, 
      { 
  headers: { 
  Authorization: "Bearer " + accessToken
Content-Length: {length of request body as integer}
X-RequestDigest: "{form_digest_value}"
        },      
        
  body: body 
      }) 
      .then((response: SPHttpClientResponse): Promise<IListItem>=> { 
  return response.json(); 
      }) 
      

1 Answer 1

0

My test code for your reference:

import { Version } from '@microsoft/sp-core-library';
import {
  BaseClientSideWebPart,
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import { SPHttpClient, ISPHttpClientOptions, SPHttpClientResponse } from '@microsoft/sp-http';
import styles from './2019NoFrameworkWebPart.module.scss';
import * as strings from '2019NoFrameworkWebPartStrings';

export interface I2019NoFrameworkWebPartProps {
  description: string;
}

export default class NoFrameworkWebPart extends BaseClientSideWebPart<I2019NoFrameworkWebPartProps> {
  
  public render(): void {
    this.domElement.innerHTML = `
      <div class="${styles.NoFramework2019}">
        <div class="${styles.container}">
          <div class="${styles.row}">
            <div class="${styles.column}">
              <span class="${styles.title}">Welcome to SharePoint!</span>
              <p class="${styles.subTitle}">Customize SharePoint experiences using Web Parts.</p>
              <p class="${styles.description}">${escape(this.properties.description)}</p>
              <a href="https://aka.ms/spfx" class="${styles.button}">
                <span class="${styles.label}">Learn more</span>
              </a>
            </div>
          </div>
        </div>
        <input type="text" id="idTitle" name="Title" placeholder="Serial Number." value="test title"><br />  
        <input id="upload" type="file" /><br />  
    <button class="create-Button ${styles.button}" id="btnRegister" ><span class="${styles.label}">Submit Order</span></button>
      </div>`;
    this._setButtonEventHandlers();
    
  }
  private _setButtonEventHandlers(): void {

    this.domElement.querySelector('#btnRegister').addEventListener('click', async () => {
      
      var id = await this.createItem();
      let resultFile = document.getElementById('upload')["files"];
      var file = resultFile[0];
      var reader = new FileReader();
      
      var content;
      reader.onload = (function (file) {
        return function (e) {
      
        }
      })(file);
      reader.readAsArrayBuffer(file);
      this.upload(id,file["name"], file);
    });
  }

  protected upload(ID,name,file){
    console.log(name)
    const spOpts: ISPHttpClientOptions = {
      body:file,
      headers: {
        'Accept': 'application/json; odata=verbose',
        'Content-type': 'application/json;odata=verbose',       
      },
      
    };
    this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Developer Workbench')/items(${ID})/AttachmentFiles/add(FileName='${name}')`, SPHttpClient.configurations.v1, spOpts)
    .then(async (response: SPHttpClientResponse) => {

     await response.json().then((responseJSON: JSON) => {
        console.log(responseJSON);
      });
    });
  }
  
  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }


  protected async createItem() {
    var id;
    const spOpts: ISPHttpClientOptions = {
      body: JSON.stringify({
        "__metadata": {
          "type": "SP.Data.Developer_x0020_WorkbenchListItem"
        },
        "Title": `${document.getElementById('idTitle')["value"]} `
      }),
      headers: {
        'Accept': 'application/json;odata=verbose',
        'Content-type': 'application/json;odata=verbose',
        'odata-version': ''
      }
    };

    await this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('Developer Workbench')/items`, SPHttpClient.configurations.v1, spOpts)
      .then( async (response: SPHttpClientResponse) => {
  
         await response.json().then((responseJSON: JSON) => {

           id=responseJSON["d"].ID;
          
        })

      });
       return id;
  }   

}

You could get the full project here:https://github.com/Amos-MSFT/SharePoint-FrameWork-Demos/tree/master/2019NoFrameWork

1
  • Thank you for the support and sharing your code!
    – Samuel
    Commented Jan 29, 2021 at 3:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.