0

I tried all previous ways but none helped to me. I try to upload file via axios:

const [file, setFile] = useState(null)
setFile(event.target.files[0]);     
const uploadFile = () => {
      const formData = new FormData(); 
      formData.append('myFile', file); 
      api.createFile(formData).then(res => {
         console.log(res.data);
      })      
    }

const axios = window.axios
const BASE_API_URL = 'http://localhost:8000',
const config = { headers: { 'content-type': 'multipart/form-data'}}      
export default {
  createFile: formData =>  
    axios.post(`${BASE_API_URL}/tickets/createFile`, formData, config)
}

I already checked the 'file' variable via log and it is exists. But when i get this in laravel:

Route::post('/tickets/createFile', function (Request $request){
  return response()->json([
    'file' => $request->file('myFile')
  ]);
});

FINALLY: I get empty response which means I can't store it cause I get null value

7
  • you that you need to write upload file code laravel.com/docs/8.x/filesystem#storing-files Commented Jan 13, 2021 at 7:12
  • You are not storing the file anywhere on your system ? you just want to file name back or what? If you want to upload it then you need to save it. Commented Jan 13, 2021 at 7:16
  • @Ashu I have already tried to store it, but I get error that file is null, since I just check it for a while by sending back via response Commented Jan 13, 2021 at 7:27
  • Can you make sure if in dev tools if there's a file named myFile and it's binary? in the request data Commented Jan 13, 2021 at 7:30
  • @Ashu I have Form data and MyFile: (binary) Commented Jan 13, 2021 at 7:39

1 Answer 1

1

You are expecting the file in JSON response, but when you access the file using $request->file('myFile'), It returns an instance of Illuminate\Http\UploadedFile, and when you're returning the json, it's going to return an empty object since Illuminate\Http\UploadedFile is not converted into json like models are since it does not have the toJson() method on it.

if you dump and die $request->file('myFile')

 Route::post('/tickets/createFile', function (Request $request){
     dd($request->file('myFile'));
  });

You must be able to see your uploaded file Object. So you can proceed ahead with storing the file using Storage::put() method

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.