화요일, 12월 10, 2024
HomeLanguageSpring Ajax File upload

Spring Ajax File upload

Spring Ajax File upload

1.jsp file 중 전송부분

//버튼 클릭시
	$("#btn_file_reg").click(function() {
		var form = $('form')[0];
		var formData = new FormData(form);
		$.ajax({
		    url: 'fileuploadAjax.ajax',
		    type: 'POST',
		    data:formData,
		    contentType: false,
		    processData: false,
		    success: function(data){
		    	alert('업로드 성공');
		    	
		    },
		    error: function(e){
		        alert(e.reponseText);
		    }
		});
	});

2.Java Controller 부분

	@RequestMapping(value = "fileuploadAjax",method = RequestMethod.POST)
	public void fileuploadAjax(@RequestParam("btn_file") MultipartFile fileupload,
									Model model) {
		
                String ofn = fileupload.getOriginalFilename();

		System.out.println("File_size : " + fileupload.getSize());
		System.out.println("File_ext : " + ofn.indexOf(".") > -1 ? ofn.substring(ofn.lastIndexOf(".") + 1) : "");
		System.out.println("File_name : " + ofn);

                InputStream stream = null;
                OutputStream bos = null;

                UUID uuid = UUID.randomUUID();
                String tempFileName uuid.toString();
                String realPath = "/fileupload";
    try
    {
      stream = fileupload.getInputStream();

      bos = new FileOutputStream(realPath + "/" + tempFileName);
      int bytesRead = 0;
      byte[] buffer = new byte[8192];
      while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
        bos.write(buffer, 0, bytesRead);
      }
      bos.close();
      stream.close();

      l.info("The file has been written to [{}]", tempFileName);
    }
    catch (FileNotFoundException e) {
      e.printStackTrace();

      if (stream != null)
        try {
          stream.close();
          stream = null;
        } catch (Exception localException) {
        }
      if (bos != null)
        try {
          bos.close();
          bos = null;
        }
        catch (Exception localException1)
        {
        }
    }
    catch (IOException e)
    {
      e.printStackTrace();

      if (stream != null)
        try {
          stream.close();
          stream = null;
        } catch (Exception localException2) {
        }
      if (bos != null)
        try {
          bos.close();
          bos = null;
        }
        catch (Exception localException3)
        {
        }
    }
    finally
    {
      if (stream != null)
        try {
          stream.close();
          stream = null;
        } catch (Exception localException4) {
        }
      if (bos != null)
        try {
          bos.close();
          bos = null;
        }
        catch (Exception localException5) {
        }
    }

	}	

3.Spring xml 설정중

	
		
			10000000
		
	
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular