簡體   English   中英

客戶端生成 CSV 文件,使用 Angular POST 發送,通過 PHP 后端保存服務器端

[英]Generate CSV file client side, send using Angular POST, save server side through PHP backend

情況:客戶有一個現有的 windows 應用程序,它使用 csv 文件來回傳輸數據,並希望以這種方式持續存在。

挑戰:從服務器地址讀取 CSV 數據后,處理數據並生成新的 CSV 文件並將其上傳到“后端”。

我嘗試過的:我已經閱讀了幾乎所有關於上傳文件的 SO 帖子,但問題是如果我只使用測試數據。 即讀取文件,重命名並保存到后端它似乎不起作用?

我使用下面的代碼來獲取文件的 blob,這工作正常,我可以在檢索數據后對其進行操作:

getCsvData3(url: string) {
        let httpOptions: any = {
            //observe: 'response',
            headers: new HttpHeaders({ 'Content-Type': 'application/octet-stream' }),
            params: new HttpParams(),
            responseType: 'response'
        }
                     
        return this.httpClient.get<string>(url, httpOptions);
    }

現在我嘗試通過簡單地重新創建File object 並將其附加到傳出進程來對此進行測試。 使用:

const type = { type: data.body.type };
const blob = new Blob([data.body], type);
const file = this.blobToFile(blob, 'test.csv')

blobToFile樣子(我嘗試了幾個選項來做到這一點無濟於事):

blobToFile(theBlob: Blob, fileName: string): File {
        var b: any = theBlob;
        //A Blob() is almost a File() - it's just missing the two properties below which we will add
        b.lastModifiedDate = new Date();
        b.name = fileName;

        //Cast to a File() type
        return <File>theBlob;
    }

隨后,我將文件附加到httpClient.Post()調用:

uploadFile(file: File, fileNum: number) {
        const formData = new FormData();
        formData.append("the_file", file, file.name);
        this.dataService.uploadWithProgress(formData)
            .subscribe(event => {
                if (event.type === HttpEventType.UploadProgress) {
                    console.log(Math.round(100 * event.loaded / event.total));
                    //let percentUploaded = Math.round(100 * event.loaded / event.total);
                } else if (event instanceof HttpResponse) {
                    console.log(file.name + ', Size: ' + file.size + ', Uploaded URL: ' +         event.body.link);
                    //this.fileUploadSuccess();
                }
            },
                err => console.log(err)
            );
    }

但是無論我嘗試什么,我都無法正常工作?

我也嘗試過使用 NativeScript 的 MediaFilePicker 但這也會帶來各種噩夢? 看到這個問題。

我有一個 NativeScript 核心應用程序,它上傳一個 JSON 文件,並由主機上的一個小 PHP 文件接收/處理。 您可以忽略身份驗證代碼,您必須轉換為 Angular,但這至少應該作為一個工作示例:

/**
* Post app's eventData object to the web, so that it may live-update apps in the field. 
* Uses basic authentication; requires .htaccess and .htpasswd files in host directory
* @param {object} eventData - app's event-specific data object, from event-data.js
* @return void
*/
exports.postEventData = function (eventData) {

  dialogs.confirm({
    title: "myutils.postEventData",
    message: "Post app's eventData object to web?",
    okButtonText: "Yes",
    cancelButtonText: "No"
  }).then((result) => {
    if (result) { // if Yes selected

      let content = JSON.stringify(eventData);

      http.request({
        url: eventData.subdomain + eventData.postPath, // path to receive.php
        method: "POST",
        headers: {
          "Content-Type": "application/octet-stream",
          "Authorization": "Basic " + credentials,
        },
        content: content
      }).then((response) => {
        console.log(response.content.toString());
        dialogs.alert({
          title: "myutils.postEventData",
          message: "EventData posted successfully.",
          okButtonText: "OK"
        }).then(() => { return; });
      }, (err) => {
        console.log(err);
        dialogs.alert({
          title: "myutils.postEventData",
          message: "EventData post failed. \n\n " + err,
          okButtonText: "OK"
        }).then(() => { return; });
      }); // end http.request
    } // end Yes selected
  }); // end confirm.then 
} // end postEventData

這是 PHP 文件:

<?php
/**
 * Receive json file via http POST request and save contents to current directory.   
 * @author David Cole <dlcole33@gmail.com>
 */

  if (empty($_POST) && empty($_GET)) { // Both POST and GET arrays should be empty 
    $outputFilename = "eventData.json";
    $outputFile = getcwd() . "/" . $outputFilename;
    $fileData = file_get_contents('php://input');
       
    $fp = fopen($outputFile, "w");
    fwrite($fp, $fileData);
    fclose($fp);
    
    if (file_exists ( $outputFile )) {
      echo "File " . $outputFile . " created on host.\n";
    } else {
      echo "File " . $outputFile . " creation failed.\n";
    }
    // echo $fileData;
  } else {
    echo '$_POST / $_GET check failed.\n';
  }
  exit();
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM