描述: input上传多张照片, 专程base64格式上传

    1. // html
    2. <div>
    3. <input id="file_input" type="file" onchange="previewImage(this, 'img_preview')" multiple>
    4. <button onclick="upload">上传</button>
    5. </div>
    6. <div id="img_preview"></div>
    7. // js
    8. <script src="zepto.min.js"></script>
    9. <script>
    10. var images = [];
    11. var uploaded = [];
    12. var upload_phase;
    13. // 图片转base64
    14. function previewImage(el, previewId) {
    15. images = [];
    16. // 页面放图片的div
    17. var preview = $('#'+previewId)
    18. preview.empty()
    19. function readAndPreview(file) {
    20. if(/\.(jpe?g|png|gif)$/i.test(file.name)) {
    21. var reader = new FileReader()
    22. reader.addEventListener("load", function(){
    23. var image = new Image();
    24. image.height = 100l
    25. image.title = file.name;
    26. image.src = this.result;
    27. // 多张图片放进数组中
    28. images.push(this.result);
    29. preview.append($(image).addclass("img-view"))
    30. }, false)
    31. reader.readAsDataURL(file)
    32. })
    33. }
    34. if(el.files){
    35. [].forEach.call(el.files, readAndPreview)
    36. }
    37. }
    38. // 上传图片
    39. function upload(phase){
    40. uploaded = []
    41. if($("file_input")[0].files[0] == undefined){
    42. alert('INPUT EMPTY')
    43. return;
    44. }
    45. [].forEach.call(images, (image) => {
    46. var formData = new FormData()
    47. formData.append("base64Image", image)
    48. var url = "https://b612-fs.snowcam.cn/v1/event/vision/face/upload-only";
    49. $.ajax({
    50. type: "POST",
    51. url: url,
    52. data: formData,
    53. dataType: "text",
    54. processData: false,
    55. contentType: false,
    56. headers: {Accept: "*/*"},
    57. timeout: 30 * 60 * 60 * 1000,
    58. success: function (response) {
    59. // success
    60. },
    61. error: function (e) {
    62. console.log("ERROR : " + e.responseText);
    63. }
    64. });
    65. })
    66. }
    67. </script>