首页 > 解决方案 > React Native (Expo) 上传文件

问题描述

我正在尝试使用 expo-image-picker 从反应本机应用程序上传选择的文件,但在后端我什么都看不到。

一开始我使用了这个解决方案,但是那里的 IFormFile 是空的。

[HttpPost]
    public IActionResult Upload([FromBody] ReqFile reqFile)
    {
        try
        {
            using (var ms = new MemoryStream())
            {
                reqFile.file.CopyTo(ms);
                var fileBytes = ms.ToArray();

                fileBytes = _fileService.AsJpeg(fileBytes);
                fileBytes = _fileService.Resize(fileBytes, 500);
                fileBytes = _fileService.Compress(fileBytes);

                var fileGuid = _fileService.Upload(fileBytes, reqFile.file.ContentType);
                return Ok(fileGuid.ToString());
            }
        }
        catch (Exception ex)
        {
            return BadRequest();
        }
    }

DTO 在哪里

public class ReqFile {
    public IFormFile file {get; set;}
}

图像选择器功能是

export const getImageUUID = async (imagePickerResult) => {
// ImagePicker saves the taken photo to disk and returns a local URI to it
let localUri = imagePickerResult.uri;
let filename = localUri.split("/").pop();

// Infer the type of the image
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;

let formData = new FormData();

const d = {
  uri: localUri,           
  name: filename,
  type: type
}

formData.append("file", d);

return await axios.post(FILE_URI,formData,
  {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Accept': 'application/json'
    }
  });
};

现在我正在尝试使用 blob 解决它

export const getImageUUID = async (imagePickerResult) => {
// ImagePicker saves the taken photo to disk and returns a local URI to it
let localUri = imagePickerResult.uri;
let filename = localUri.split("/").pop();

// Infer the type of the image
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;

let formData = new FormData();

const rp = await fetch(localUri);
const blob = await rp.blob();

formData.append("file", blob);

return await axios.post(FILE_URI,formData,
  {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Accept': 'application/json'
    }
  });
};

但是我在请求文件 截图时遇到了未找到的错误

标签: react-nativeasp.net-coreexpo

解决方案


推荐阅读