Wednesday 20 February 2019

Laravel force download api + vue force download on different port + elquoent or statement + JS get file extension

Laravel OR query:

https://laracasts.com/discuss/channels/eloquent/use-orwhere-in-eloquent

$camps = $field->camps()->where('status', 0)->where(function ($q) {
    $q->where('sex', Auth::user()->sex)->orWhere('sex', 0);
})->get();


Vue && laravel force download on different port

Laravel:

        // Init
        $file_path          = '/home/jxiang' . $request->file_path;
        $file_extension     = pathinfo($file_path, PATHINFO_EXTENSION);
        $file_name          =  $request->file_name . '.' . $file_extension;

        $file_content       = file_get_contents($file_path);

        return \Response::make(
            $file_content,
            200,
            array(
                'Content-Type' => 'application/octet-stream',
                'Content-Disposition' => 'attachment;filename='. $file_name,
                'Access-Control-Allow-Origin' => 'http://127.0.0.1:8080', // Manually set
                'Access-Control-Allow-Methods' =>'GET, PUT, POST, DELETE, HEAD, PATCH',
                'Access-Control-Allow-Headers' =>'*',)
            );



 'application/octet-stream',


Vue front end ðŸ‘Œ
downloadContract(booking) {
  this.$http.get(this.appApiPath + '/download_contract/' + booking.id, {responseType: 'arraybuffer'})
    .then(response => {
      this.downloadFile(response, 'customFilename')
    }, response => {
      console.warn('error from download_contract')
      console.log(response)
      // Manage errors
      }
    })
},

downloadFile(response, filename) {
  // It is necessary to create a new blob object with mime-type explicitly set
  // otherwise only Chrome works like it should
  var newBlob = new Blob([response.body], {type: 'application/pdf'})

  // IE doesn't allow using a blob object directly as link href
  // instead it is necessary to use msSaveOrOpenBlob
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(newBlob)
    return
  }

  // For other browsers:
  // Create a link pointing to the ObjectURL containing the blob.
  const data = window.URL.createObjectURL(newBlob)
  var link = document.createElement('a')
  link.href = data
  link.download = filename + '.pdf'
  link.click()
  setTimeout(function () {
    // For Firefox it is necessary to delay revoking the ObjectURL
    window.URL.revokeObjectURL(data)
  }, 100)
},




Neat trick to get file externsion using js:

var input = 'jquery.somePlugin.v1.6.3.js';
var period = input.lastIndexOf('.');
var pluginName = input.substring(0, period);
var fileExtension = input.substring(period + 1);
console.log(pluginName, fileExtension);

https://stackoverflow.com/questions/29825464/javascript-split-split-string-by-last-dot



crucial part is responsetype : arraybuffer to get binary from server  

downloadFile() {
  this.$http.get(this.appApiPath + '/testpdf', {responseType: 'arraybuffer'})
    .then(response => {
      let blob = new Blob([response.data], { type: 'application/pdf' })
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'test.pdf'
      link.click()
    })
}
vue-resource:
this.$get(
   'http://link-to-my-image', 
   { responseType: 'arraybuffer', headers: this.http_headers }
)
.then(res => {
   console.log("Response body ArrayBuffer: ", res.body)
})




An empty responseType string is treated the same as "text" , the default type (therefore, as a DOMString . "arraybuffer" The response is a JavaScriptArrayBuffer containing binary data. "blob" The response is a Blob object containing the binary data.Mar 6, 2018



No comments:

Post a Comment