I am trying to upload image file (any type) from react native Android app frontend to C# backend code.
Here is my react native code:
import * as ImagePicker from "expo-image-picker";
export default function AdminPortal() {
const [image, setImage] = useState<ImagePicker.ImagePickerResult | null>(null);
const handleSubmit = () => {
const formData = new FormData();
if (image && !image.canceled) {
const fileUri = image.assets[0].uri;
const fileType = image.assets[0].type;
const fileName = image.assets[0].fileName;
formData.append("file", {
uri: fileUri,
type: fileType,
name: fileName,
});
}
fetch('http://192.168.4.25:7018/post', {
method: 'POST',
body: formData,
})
.then((response) => response.json())
.then((response) => {
console.log('upload succes', response);
})
.catch((error) => {
console.log('upload error', error);
});
Alert.alert("Data submitted", JSON.stringify(data));
// navigation.goBack();
};
return (
<SafeAreaView style={styles.container}>
<Text style={styles.header}>Admin Page</Text>
<Pressable style={styles.button} onPress={handleImageUpload}>
<Text style={styles.buttonText}>Upload Image</Text>
</Pressable>
{image && !image.canceled && (
<Text>Image selected: {image.assets[0].fileName}</Text>
)}
<Pressable style={styles.submitButton} onPress={handleSubmit}>
<Text style={styles.buttonText}>Submit</Text>
</Pressable>
</SafeAreaView>
Here is my backend code for C#:
[HttpPost]
public async Task<ActionResult> Create(IFormFile file)
{
try
{
var imageUrl = new ImageHandler(_cloudinary).ImageUploader(file);
_logger.LogInformation("A new post has been created");
return Ok(new { message = "A new post has been created" });
}
catch (Exception ex)
{
return StatusCode(500, new { message = ex.Message });
}
}
Other information:
- I can see my other API are working fine with other types and the app is connected to the back end.
- The back end code looks ok as I can also hit the breakpoint from PostMan with a file selected.
Can anyone please help me with this been nearly two days trying to solve this?
Try using [FromForm]
in your method parameters.
public async Task<ActionResult> Create([FromForm] IFormFile file)
{
//...
}
[FromForm]
represent the files and from datas which you send from client. If you want to understand check this reading.
3