Answer the question
In order to leave comments, you need to log in
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));
};
<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>
Answer the question
In order to leave comments, you need to log in
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);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question