2016-11-24 35 views
2

我有限定的形式:上傳的圖像與獲取

<form method="POST" onSubmit={this.handleSubmit.bind(this)} enctype="multipart/form-data"> 

用於提交事件處理程序定義爲這樣:

handleSubmit(event) 
    { 
     event.preventDefault(); 
     var FormData = require('form-data'); 
     var form = new FormData(); 

     form.append('nome', this.refs.name.value); 
     form.append('phone', this.refs.phone.value); 
     form.append('address', this.refs.address.value); 
     form.append('mail', this.refs.mail.value); 
     form.append('type', 'file'); 
     form.append('photo', this.refs.photo.value); 

     const {dispatch} = this.props; 
     dispatch(fetchByArray(form)); 
    } } 

fetchByArray(形式):

export function fetchByArray(form) { 
    return function(dispatch) { 
     return fetch(`http://my_domain/api`, { 
      method: "POST", body: form }) 
      .then(response => response.json()) 
      .then(json => dispatch(receiveByQuerystring1(json))); 
    } } 

如果所有的參數都是字符串,但是如果我嘗試指定一個文件,則會生效,因爲我的api處理程序沒有獲取該文件,所以出現錯誤。

在後端$request->file('photo')是空的。這裏可能是我的問題?

+0

你可能要指定一個不同的選項在你的表單數據中,如下所示https://github.com/github/fetch#file-upload –

+0

請參閱https://gist.github.com/ebidel/2410898 – David

回答

-1

您需要閱讀http://www.faqs.org/rfcs/rfc1867.html文件發送api的規則。我們在客戶端文件系統相關操作中有很多限制。

我將介紹如何使用對我的作品作出反應 - 終極版 - 佐賀

  1. 我有輸入類型的文件是這樣的:

<input 
 
    type="file" 
 
    onChange={this.onChange} 
 
/>

  • 和onChange處理程序(選擇文件後立即上傳)
  • this.props.registerFile(this.state.id, event.target.files[0]);

  • 創建的文件上傳請求
  • const formData = new FormData(); 
     
         formData.append('file', file.get('file')); //event.target.files[0] data going here 
     
        
     
         const requestOptions = { 
     
         method: 'POST', 
     
         body: formData, 
     
         credentials: 'same-origin', 
     
         }; 
     
    
     
    const result = yield call(xhrRequest, requestURL, requestOptions); 
     
    
     
    function request(url, options) { 
     
        return fetch(url, options) 
     
        .then(checkStatus) 
     
        .then((response) => { 
     
         let result = response; 
     
         return result; 
     
        }) 
     
        .then((data) => ({ data })) 
     
        .catch((err) => ({ err }));