2
curl -F 'data=@./resourcesByFileId.png' -F 'props={"title":"resource title"}' http://localhost:27583/resources
 async create(fd: FormData) {
    const resp = await axios.post<ResourceGetRes>(
      ApiUtil.baseUrl('/resources'),
      fd,
      {
        headers: fd.getHeaders(),
      },
    )
    return resp.data
  }
  
    const fd = new FormData()
    const path = resolve(__dirname, '../resource/resourcesByFileId.png')
    console.log('test create: ', path)
    fd.append('props', JSON.stringify({ title: '图片标题' }))
    fd.append('data', createReadStream(path))
    await resourceApi.create(fd)

I tried it with form-data and axios and it blew up

Original question https://discourse.joplinapp.org/t/how-to-use-joplin-api-resources-id-file/11333/3?u=rxliuli


I tried fetch and it succeeded immediately. Is there any difference between the two below?

  describe('diff fetch and axios', () => {
    function getFormData() {
      const fd = new FormData()
      const path = resolve(__dirname, '../resource/resourcesByFileId.png')
      const title = 'image title'
      fd.append('props', JSON.stringify({ title: title }))
      fd.append('data', createReadStream(path))
      return fd
    }

    it('test create by fetch', async () => {
      const fd = getFormData()
      const resp = await fetch(ApiUtil.baseUrl('/resources'), {
        method: 'post',
        body: fd,
      })
      const json = await resp.json()
      console.log('json: ', json)
    })
    it.skip('test create by axios', async () => {
      const fd = getFormData()
      const resp = await axios.post(ApiUtil.baseUrl('/resources'), fd, {
        headers: fd.getHeaders(),
      })
      console.log('resp.data: ', resp.data)
    })
  })
rxliuli
  • 165
  • 1
  • 11

2 Answers2

0

From curl documentation

-F, --form <name=content>

(HTTP SMTP IMAP) For HTTP protocol family, this lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content-Type multipart/form-data according to RFC 2388.

So, this is the classic scenario when user fill a form, select a file and press submit or upload.

Check this answer to understan how curl works:

curl -v -F key1=value1 -F upload=@localfilename URL

After that, you might be able to understand and replicate it with axios:

var bodyFormData = new FormData();
bodyFormData.append('userName', 'Fred');
bodyFormData.append('image', imageFile);

axios({
    method: 'post',
    url: 'myurl',
    data: bodyFormData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  .then(function(response) {
    //handle success
    console.log(response);
  })
  .catch(function(response) {
    //handle error
    console.log(response);
  });

Review these links:

JRichardsz
  • 14,356
  • 6
  • 59
  • 94
0
            import React from 'react'
            import axios, { post } from 'axios';

            class SimpleReactFileUpload extends React.Component {

              constructor(props) {
                super(props);
                this.state ={
                  file:null
                }
                this.onFormSubmit = this.onFormSubmit.bind(this)
                this.onChange = this.onChange.bind(this)
                this.fileUpload = this.fileUpload.bind(this)
              }

              onFormSubmit(e){
                e.preventDefault() // Stop form submit
                this.fileUpload(this.state.file).then((response)=>{
                  console.log(response.data);
                })
              }

              onChange(e) {
                this.setState({file:e.target.files[0]})
              }

              fileUpload(file){
                const url = 'http://example.com/file-upload';
                const formData = new FormData();
                formData.append('file',file)
                const config = {
                    headers: {
                        'content-type': 'multipart/form-data'
                    }
                }
                return  post(url, formData,config)
              }

              render() {
                return (
                  <form onSubmit={this.onFormSubmit}>
                    <h1>File Upload</h1>
                    <input type="file" onChange={this.onChange} />
                    <button type="submit">Upload</button>
                  </form>
               )
              }
            }



            export default SimpleReactFileUpload