V
V
Vlad Yanukovich2021-08-24 22:55:07
typescript
Vlad Yanukovich, 2021-08-24 22:55:07

How to send a file and return the data?

Hello ladies and gentlemen. I need your help.

I can not understand how to work with forms in TS.

I am making an application for creating and reading qr codes. Everything is ready except the last option for processing the qr code - downloading the file.

I use the API ( https://goqr.me/api/doc/read-qr-code/ ), a link to read the qr code, there is an option below with uploading a file through a regular HTML form. It works, however there is a redirect where the response is already on the page.

I'm trying to rewrite this all using state. My actions: through the input, I upload the file (onChange handler) and save it in the state. Next, I take this file from the state and put it in the body of the POST request. well, as you understand, nothing comes out - bad request 400.

Below I will attach the code how I do it, don’t scold me much, I just recently started using TS.
Help me solve the problem: you need to send a photo with a qr code to the address that will be in the request body, and is it possible to somehow return the result and display it on the page after? (without a redirect, but dynamically display it under the input, for example)

const [file, setFile] = useState<FileList | any | string>()  //тут хранится файл который гружу в инпут

function uploadFile(e: React.ChangeEvent<HTMLInputElement>) {  //функция обработки загрузки файла
        setFile(e.target.files[0]) //тут 0 потому что полный ответ приходит в FileList и я забираю первый элемент (единственный )
    }
 const handleSubmission = async (e: React.FormEvent<HTMLFormElement>) => {
       e.preventDefault()
       
    const formData = new FormData();

    formData.append('File',  file); //тут закидываю тот файл что загрузил через инпут

    await fetch('http://api.qrserver.com/v1/read-qr-code/', {
        method: 'POST',
        body: formData,
                                headers: { 'Content-Type': 'multipart/form-data' },               
      }
    )
      .then((res) => res.json())
      .then((result) => console.log(result))
      .catch((error) => console.error( error));
  };


Here is the form itself that I am trying to process (almost does not differ from the one offered on the site):
<form onSubmit={handleSubmission} >

                    <input type="file" name="file" className="upload-input" id="upload-file" onChange={uploadFile}/>

                    <label className="upload-btn" htmlFor="upload-file" >   Upload your QR code  </label>              
  
                   <button type="submit">send</button>
                </form>


PS loading input is hidden - I open the loading window by label

In this flow of information I will repeat what I am trying to solve:
1. Processing and displaying information on the page from the post request.
2. do it all without a redirect, as happens with the example of an html form on a site with an API

, I hope someone can help me at such a late hour

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-08-24
@Vladislav6

1) const [file, setFile] = useState< File | null >(null);
2) in the documentation (clause 3.2, an example to it) there is a MAX_FILE_SIZE parameter, apparently mandatory.
3) "file", not "File". The server is most likely case sensitive to the field names
total:

formData.append('MAX_FILE_SIZE', '12345678'); // или сколько там
formData.append('file',  file);

4) Is there really no js-library for parsing qr, so that you do not have to depend on the Internet?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question