【问题标题】:Validation error while calling api with files使用文件调用 api 时出现验证错误
【发布时间】:2019-02-08 08:29:52
【问题描述】:

我将 react、redux 用于后端,将 jsx 用于需要将图像文件作为用户输入并将其发送到某个 api 以上传的项目。 这是我的代码:

函数发布(请求){

let config = request.server.app.config;
if (!imageEditClient) {
    imageEditClient = new HttpClient('imageEditClient', {
        timeout: 5000,
        connectionTimeout: 5000,
        baseUrl: `${config.get('api.baseUrl')}`
    });
}

request.log(['UploadImage payload coming from request'], request.payload);

let payload = request.payload;
let suffix = 'ImageUpload';
// let blob = new Blob([request.params.imageFile], {type: 'image/jpeg'});

let form = new FormData({maxDataSize: 20971520});

    let form = new FormData({maxDataSize: 20971520});

    const options = {
        payload,
        headers: {
            'If-Match': '*',
            'Content-Type': undefined

        }
    };

    form.append('file', request.params.imageFile);
    form.append('json', request.params.dataFile);

    return imageEditClient.post(suffix, options, form).then(mutate)
        .catch((err) => {
            err.message = `ImageEditService: ${err.message} - ${suffix}.`;
            throw err;
        });

}

我收到以下错误:

[1] "value" must be a Function
[HAPIJS]     at Object.exports.process (/Users/alnc/ha_projects/content-catalog-node-ui/node_modules/joi/lib/errors.js:181:19)
[HAPIJS]     at iterate (/Users/alnc/ha_projects/content-catalog-node-ui/node_modules/items/lib/index.js:36:13)
[HAPIJS] [2018-09-03 09:20:51,836](53611) [log] [warn] - shutting down.
[HAPIJS] Debug: internal, implementation, error 
[HAPIJS]     ValidationError: Uncaught error: {
[HAPIJS]   "_overheadLength": 206,
[HAPIJS]   "_valueLength": 26,
[HAPIJS]   "_valuesToMeasure": [],
[HAPIJS]   "writable": false,
[HAPIJS]   "readable": true,
[HAPIJS]   "dataSize": 0,
[HAPIJS]   "maxDataSize": 20971520,
[HAPIJS]   "pauseStreams": true,
[HAPIJS]   "_released": false,
[HAPIJS]   "_streams": [
[HAPIJS]     "----------------------------703740497184449347716405\r\nContent-Disposition: form-data; name=\"file\"\r\n\r\n",
[HAPIJS]     "[object Blob]",
[HAPIJS]     function () { [native code] },
[HAPIJS]     "----------------------------703740497184449347716405\r\nContent-Disposition: form-data; name=\"json\"\r\n\r\n",
[HAPIJS]     "[object Blob]",
[HAPIJS]     function () { [native code] }
[HAPIJS]   ],
[HAPIJS]   "_currentStream": null,
[HAPIJS]   "_boundary": "--------------------------703740497184449347716405",
[HAPIJS]   "value" [1]: -- missing --
[HAPIJS] }

我不清楚这个错误。 有什么想法吗?

【问题讨论】:

    标签: javascript reactjs redux react-redux jsx


    【解决方案1】:

    您不能像这样使用来自 react 的表单数据,您应该首先处理您的 imageFile 并从请求的图像中生成 e Blob 对象,然后将您刚刚创建的图像的 blob 对象发送到表单数据对象(附加此 Blob到表单数据的“文件”属性,而不是直接附加请求的图像),这些函数可以帮助您将图像转换为 blob 工作:

          function dataURLtoBlob(dataURL) {
            const binary = atob(dataURL.split(',')[1]);
            const array = [];
            const length = binary.length;
            let i;
            for (i = 0; i < length; i++) {
              array.push(binary.charCodeAt(i));
            }
            return new Blob([new Uint8Array(array)]);
          }
    

    接下来的两个函数是从您输入的图像创建一个图像并从文件读取器中获取一个 dataUrl,以便在上述函数中使用它来转换为 blob 过程,第一个函数是主要函数从您输入用户图像的位置调用:

          export function processFile(file) {
            return new Promise((resolve, reject) => {
              try {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onloadend = async function() {
                  const processedFile = await handleImage(reader.result);
                  resolve(processedFile);
                };
              } catch (err) {
                reject(err);
              }
            });
          }
    

    然后:

          async function handleImage(dataURL) {
            const image = new Image();
            image.src = dataURL;
            return new Promise((resolve, reject) => {
              image.onload = function() {
                  resolve(dataURLtoBlob(dataURL, fileType));
              };
              image.onerror = reject;
            });
          }
    

    对于其余代码,如果您从输入中获取图像,您可以使用 event.target.files[0] 从附加到文件输入更改的事件中将其作为文件变量发送到上面的函数 processFile 中,然后将其附加到您的表单数据中: 第一:

      imageData = await processFile(fileData);
    

    然后从您的表单数据代码中:

      form.append('file', imageData);
    

    【讨论】:

    • 您好 Mehrnaz,感谢您的快速回复。 imageFile 已在客户端转换为 blob。让 blob = new Blob([imageFile], {type: 'image/jpeg'});这难道不是正确的做法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    相关资源
    最近更新 更多