te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Uploading an image with redux-form - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uploading an image with redux-form - Stack Overflow

programmeradmin3浏览0评论

I have a react.js redux-form that works and posts data back to my API but I need to also allow the submitter to upload an image with the form, ideally with a preview. I struggled a bit and have arrived at dropzone.js but I can't seem to get my form to actually POST the image data back.

render () {
  const FILE_FIELD_NAME = 'files';

    const renderDropzoneInput = (field) => {
      const files = field.input.value;
      return (
        <div>
          <Dropzone
            name={field.name}
            onDrop={( filesToUpload, e ) => field.input.onChange(filesToUpload)}
          >
            <div>Try dropping some files here, or click to select files to upload.</div>
          </Dropzone>
          {field.meta.touched &&
            field.meta.error &&
            <span className="error">{field.meta.error}</span>}
          {files && Array.isArray(files) && (
            <ul>
              { files.map((file, i) => <li key={i}>{file.name}<img src={file.preview}/></li>) }
            </ul>
          )}
        </div>
      );
    }

    return (
        <form onSubmit={this.props.handleSubmit(this.onSubmit)}>
          <div className="form-group">
            <Field name="files" ponent={renderDropzoneInput} />
          </div>
          <button type="submit" className="btn btn-default">Submit</button>
        </form>
    );
}

The files variable does get POSTed back to the API which is great but it contains the following:

[preview=blob:http://localhost:3000/bed3762e-a4de-4d19-8039-97cebaaca5c1]

Can anyone suggest how I get the actual binary data in to that variable please?

The full code is available here .js

I have a react.js redux-form that works and posts data back to my API but I need to also allow the submitter to upload an image with the form, ideally with a preview. I struggled a bit and have arrived at dropzone.js but I can't seem to get my form to actually POST the image data back.

render () {
  const FILE_FIELD_NAME = 'files';

    const renderDropzoneInput = (field) => {
      const files = field.input.value;
      return (
        <div>
          <Dropzone
            name={field.name}
            onDrop={( filesToUpload, e ) => field.input.onChange(filesToUpload)}
          >
            <div>Try dropping some files here, or click to select files to upload.</div>
          </Dropzone>
          {field.meta.touched &&
            field.meta.error &&
            <span className="error">{field.meta.error}</span>}
          {files && Array.isArray(files) && (
            <ul>
              { files.map((file, i) => <li key={i}>{file.name}<img src={file.preview}/></li>) }
            </ul>
          )}
        </div>
      );
    }

    return (
        <form onSubmit={this.props.handleSubmit(this.onSubmit)}>
          <div className="form-group">
            <Field name="files" ponent={renderDropzoneInput} />
          </div>
          <button type="submit" className="btn btn-default">Submit</button>
        </form>
    );
}

The files variable does get POSTed back to the API which is great but it contains the following:

[preview=blob:http://localhost:3000/bed3762e-a4de-4d19-8039-97cebaaca5c1]

Can anyone suggest how I get the actual binary data in to that variable please?

The full code is available here https://github./rushughes/dsloracle/blob/master/client/src/ponents/LandCreate/index.js

Share Improve this question edited Jan 6, 2018 at 9:41 Vikas Yadav 3,3542 gold badges22 silver badges22 bronze badges asked Jan 6, 2018 at 5:39 RusHughesRusHughes 1,1812 gold badges12 silver badges18 bronze badges 1
  • Can you point me to the file where you receive the form data on the server side? – zarcode Commented Jan 9, 2018 at 19:10
Add a ment  | 

3 Answers 3

Reset to default 5 +100

I recently had a similar issue and solved it by using the FileReader API to convert the blob url to Base64 (can also convert to binary string).

Then you send the Base64 or binary string to the server.

My example code:

onDrop(acceptedFiles: any): any {

    let images: any = this.state.Images;

    acceptedFiles.forEach((file: any) => {

        const reader: FileReader = new FileReader();
        reader.onload = () => {
            const fileAsBase64: any = reader.result.substr(reader.result.indexOf(",") + 1);
            images.push(fileAsBase64);
        };

        reader.onabort = () => console.log("file reading was aborted");
        reader.onerror = () => console.log("file reading has failed");

        reader.readAsDataURL(file);
    });

    this.setState(prevState => ({   
         Images: images,
    }));
}

If you want to send a binary string instead of base64 change reader.readAsDataURL(file); to reader.readAsBinaryString(file);

and this line: const fileAsBase64: any = reader.result.substr(reader.result.indexOf(",") + 1); can be simplified to const file: any = reader.result;

Here are the steps for file-upload feature: (How to handle image data in your API)

  • Append your redux-form values to the FormData instance.

    let formData = new FormData();
    formData.append('myFile', files[0]);
    
  • Send multipart/form-data request from Client to your API with axios or fetch library:

  • Receive that multipart/form-data request in your API, process it with multer and then write the file to the disk storage or memory storage as follows:

    $ npm install --save multer
    
    const multer  = require('multer')
    
    const storage = multer.diskStorage({
      destination: function (req, file, cb) {
      cb(null, '/tmp/my-uploads')
     },
      filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now())
     }
    })
    
    const upload = multer({ storage: storage })
    
    const app = express()
    
    app.post('/upload', upload.single('myFile'), (req, res, next) => {
      // req.file is the `myFile` file
      // req.body will hold the text fields, if there were any
     })
    
  • (Optional) Serve files directly from your API with Express Serve-Static

There are solutions available for React.js with Dropzone. Please refer to following:

http://reactdropzone.azurewebsites/example/

Which code can be found here: https://react.rocks/example/React-Dropzone

Further more these solutions will also assist you in some way, to get out of the problem:

https://github./react-dropzone/react-dropzone

https://medium./technoetics/handling-file-upload-in-reactjs-b9b95068f6b

http://blog.mauriziobonani./dropzone.js-react.js-and-fluxxor-integration/

https://css-tricks./image-upload-manipulation-react/

https://www.reddit./r/reactjs/ments/6k6fjr/reactdropzone_integration_with_react/

发布评论

评论列表(0)

  1. 暂无评论