POST immediately after select a file

后端 未结 4 1818
天命终不由人
天命终不由人 2020-12-14 06:48

I have the following HTML code

Key filename:
4条回答
  •  余生分开走
    2020-12-14 07:32

    In case you don't want or need to submit the whole form on file input select, then you can do this to send only the file:

    $(document).ready(function (e) {
    	$("#uploadImage").on('change',(function(e) {
    		// append file input to form data
    		var fileInput = document.getElementById('uploadImage');
    		var file = fileInput.files[0];
    		var formData = new FormData();
    		formData.append('uploadImage', file);
    
    		$.ajax({
    			url: "ajaxupload.php",
    			type: "POST",
    			data: formData,
    			contentType: false,
    			cache: false,
    			processData:false,
    			success: function(data) {
    				if(data=='invalid') {
    					// invalid file format.
    					$("#err").html("Invalid File !").fadeIn();
    				}
    
    				else {
    					// view uploaded file.
    					$("#preview").html(data).fadeIn();
    					$("#form")[0].reset();
    				}
    			},
    			error: function(e) {
    				$("#err").html(e).fadeIn();
    			}
    		});
    	}));
    });
    
      
      
      
      

    So first you get the input file element with getElementById(), then you append to FormData, then send the FormData as data in your ajax call. Do the server side upload processing in ajaxupload.php.

提交回复
热议问题