2016年1月12日 星期二

Ajax上傳檔案Sample

早期的瀏覽器並不支援透過Ajax上傳檔案的作法,因此常都需要透過Flash的元件來做到一些有互動性的檔案上傳。

在瀏覽器開始支援後(對,我就是說IE!)Ajax上傳檔案的作法才開始應用,所以需要注意瀏覽器的版本。

瀏覽器版本資訊

IE
FIREFOX
CHROME
SAFARI
OPERA
10.0+
4.0+
7.0+
5+
12+


Sample Code


<!-- HTML -->

<input type='file' name='upload' id='file-select' />

<!-- Javascript -->

<script>

    var fileSelect = document.getElementById('file-select');

    // Get the selected files from the input.

    var files = fileSelect.files;//It’s an array.

    // Create a new FormData object.

    var formData = new FormData();

    // Loop through each of the selected files.

    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        // Check the file type.可利用type屬性篩選,這裡只取圖片
        if (!file.type.match('image.*')) {
            continue;
        }

        // Add the file to the request.這裡的第一個參數等於QueryStringname,第二個參數等於Value
        formData.append('upload', file, file.name);

    }

    //接著可透過JQuery或是自己弄個XMLHttpRequest的方式Send Form

    //JQuery
    $.ajax({
        url: '/WebApp/uploadFile.action',//php,jsp and etc..
         type: 'POST',
        data: formdata,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR) {
            // Handle errors here
            console.log('Success: ' + textStatus);
            //STOP LOADING SPINNER

        },

        error: function(jqXHR, textStatus, errorThrown) {
            // Handle errors here
            console.log('Errors: ' + textStatus);
            // STOP LOADING SPINNER
        }

    });



    //XMLHttpRequest
    // Set up the request.
    var xhr = new XMLHttpRequest();

    // Open the connection.
    xhr.open('POST', 'handler.php', true);

    // Set up a handler for when the request finishes.
    xhr.onload = function () {

        if (xhr.status === 200) {
            // File(s) uploaded.
             //uploadButton.innerHTML = 'Upload';
            alert('Upload Success!');
        } else {             alert('An error occurred!');         }     };     // Send the Data.     xhr.send(formData); </script>


參考資料


2016年1月10日 星期日

檢查文字檔案編碼

最近做了針對純文字檔案(.txt)的Parse工作,由於取得的txt檔案有可能是utf-16編碼

因此若用一般IO方式讀檔案

new BufferedReader(fileReader);

會出現多餘的空白導致判斷有問題,因此需要先判斷檔案的格式是什麼再改成

new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-16"));

以下是找到的java lib Sample Code,做個紀錄...

https://code.google.com/p/juniversalchardet/

import org.mozilla.universalchardet.UniversalDetector;
public class TestDetector {
  public static void main(String[] args) throws java.io.IOException {
    byte[] buf = new byte[4096];
    String fileName = args[0];
    java.io.FileInputStream fis = new java.io.FileInputStream(fileName);

    // (1)
    UniversalDetector detector = new UniversalDetector(null);

    // (2)
    int nread;
    while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
      detector.handleData(buf, 0, nread);
    }
    // (3)
    detector.dataEnd();

    // (4)
    String encoding = detector.getDetectedCharset();
    if (encoding != null) {
      System.out.println("Detected encoding = " + encoding);
    } else {
      System.out.println("No encoding detected.");
    }

    // (5)
    detector.reset();
  }
}