ajax로 파일 업로드와 여러 데이터를 한꺼번에 같이 전송

Web Development assistant·2023년 10월 21일
0

# spring

목록 보기
25/32
<div>
	<input type="text" name="name">
    <input type="text" name="age">
	<input type="file" name="uploadFile"  multiple="multiple">
	<br>
	<button>submit</button>
</div>

<script>
	$(document).ready(function(){
		$('button').on('click', function(){
			var files = $('[name=uploadFile]')[0].files;
			
			var formData = new FormData();
			
            //파일 데이터
			for(var i = 0; i<files.length; i++){
				formData.append('uploadFile', files[i]);
			}
            //나머지 데이터들...
			formData.append('name', $('[name=name]').val());
            formData.append('age', $('[name=age]').val());
			
			$.ajax({
				type: 'post',
				url : '/uploadFormAction',
				data : formData,		//formData 객체로 한 번에 전송
				contentType : false,	//파일업로드인 경우 false;
				processData : false,	//파일업로드인 경우 false;
				success : function(result){
					alert("upload");
				}
			});
			
		});
	});
</script>


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>server >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

@PostMapping("/uploadFormAction")
	public void uploadFormAction(MultipartFile[] uploadFile, @RequestParam Map<String, String> inMap,HttpServletResponse response) throws IllegalStateException, IOException {

		for(MultipartFile file : uploadFile) {
			log.info("getOriginalFilename : " +file.getOriginalFilename());
			log.info("getContentType : " +file.getContentType());
			log.info("getName : " +file.getName());
			log.info("getSize : " +file.getSize());
			
			File saveFile = new File("C:\\Users\\hjs\\Desktop\\test", "wow"+file.getOriginalFilename());
			file.transferTo(saveFile);
			
		}
		
		String name= inMap.get("name");
		int age = Integer.parseInt(inMap.get("age"));
		
		log.info("my name is {} and {}years old", name, age);
		
		response.setStatus(HttpStatus.OK.value());
	}

0개의 댓글