I’m currently working on a project involving uploading PDF files using React Native for the frontend and Laravel for the backend. However, I’m encountering an issue where the file upload is failing, and I’m receiving a 422 status code along with an AxiosError message indicating a bad request. Here’s the error message I’m seeing: “Error uploading file: AxiosError {message: ‘Request failed with status code 422’, name: ‘AxiosError’, code: ‘ERR_BAD_REQUEST’…”. Can anyone help me troubleshoot this issue? Have you encountered similar problems before, and if so, how did you resolve them? Additionally, any suggestions on where I should look for more detailed error messages or logs, especially on the server side?
React native code
import React, { useState,useContext } from 'react';
import { View, Button, Text } from 'react-native';
import * as DocumentPicker from 'expo-document-picker';
import { AuthContext } from '../context/AuthProvider';
import axiosConfig from '../helpers/axiosConfig';
const UploadPDFScreen = () => {
const [selectedFile, setSelectedFile] = useState(null);
const { user } = useContext(AuthContext);
const pickDocument = async () => {
try {
const document = await DocumentPicker.getDocumentAsync({
type: 'application/pdf',
});
const selectedFileName = document.assets[0].name; // Extract the file name
setSelectedFile({ ...document, name: selectedFileName }); // Set the file name along with other properties
} catch (error) {
console.error('Error picking document: ', error);
}
};
const uploadFile = async () => {
if (!selectedFile) {
console.error('No file selected');
return;
}
try {
const formData = new FormData();
formData.append('pdf_file', selectedFile); // Append the file directly
// Set authentication headers
axiosConfig.defaults.headers.common['Authorization'] = 'Bearer ' + user.token;
const response = await axiosConfig.post('/upload-pdf', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log('Upload success:', response.data);
} catch (error) {
console.error('Error uploading file:', error);
}
};
return (
<View>
<Button title="Select PDF File" onPress={pickDocument} />
<Button title="Upload File" onPress={uploadFile} disabled={!selectedFile} />
{selectedFile && (
<View>
<Text>Selected PDF: {selectedFile.name}</Text>
{/* Further operations with the selected PDF */}
</View>
)}
</View>
);
};
export default UploadPDFScreen;
Laravel app api
<?php
namespace AppHttpControllersApi;
use IlluminateHttpRequest;
use AppHttpControllersController;
use IlluminateSupportFacadesStorage;
use IlluminateSupportFacadesValidator;
class FileUploadController extends Controller
{
/**
* Handle the upload of a PDF file.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpJsonResponse
*/
public function uploadPdf(Request $request)
{
// Define the validation rules
$validator = Validator::make($request->all(), [
'pdf_file' => 'required|file|mimes:pdf|max:10240', // max size 10MB
]);
// Check if the validation fails
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 422);
}
// Retrieve the validated file
$file = $request->file('pdf_file');
// Store the file in the specified directory
$filePath = $file->store('public/pdfs');
// Return a successful response with the file path
return response()->json([
'file_path' => Storage::url($filePath),
'message' => 'File uploaded successfully',
], 201);
}
}