JQuery

 

 

방법1)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<title>:: AJAX 파일전송 ::</title>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<!-- <script async src="https://imgbb.com/upload.js"></script> -->
<script type="text/javascript">
    function ajaxFileUpload() {
        var form = jQuery("ajaxFrom")[0];
        var formData = new FormData(form);
        formData.append("message", "ajax로 파일 전송하기");

        var fileValue = $("#ajaxFile").val().split("\\");        
        var fileName = fileValue[fileValue.length-1].replace(/(.png|.jpg|.jpeg|.gif)$/, ''); // 파일명
        console.log("fileName : "+fileName);
        console.log("fd");
        
/*         $.get('http://127.0.0.1/aj/imgbb/key', function(data, status){
            if(status=="success"){
                
            }
           console.log(data);
           console.log(status);
       });
        
        return;
         */
        // var urlImg="http://localhost:8080/imgbb/imgs/life.jpg";
        formData.append("key", "키값");
        formData.append("image", jQuery("#ajaxFile")[0].files[0]);        
        formData.append("name", fileName);
        
        //formData.append("expiration", "");        
        
        console.log("파일 데이터");
        console.dir(jQuery("#ajaxFile")[0].files[0]);
        console.log("-------------");
        console.log(jQuery("#ajaxFile")[0].files[0]);
        
        //return;
        
        jQuery.ajax({
              url : "https://api.imgbb.com/1/upload"
            , type : "POST"
            , processData : false
             ,contentType : false
            , data : formData
            , success:function(imgbbReturn) {
            	
            	if(imgbbReturn.success==true){
            		
                	console.dir(imgbbReturn);
                	
                	var imgbb = imgbbReturn.data;
                	
                	console.log(imgbb.delete_url);
                	console.log(imgbb.display_url);
                	console.log(imgbb.expiration);
                	console.log(imgbb.id);
                	
                	console.log("imgbb.image.url : " +imgbb.image.url);
                	//image: {filename: "summerfield-336672-640-jpg.jpg", name: "summerfield-336672-640-jpg", mime: "image/jpeg", extension: "jpg", url: "https://i.ibb.co/KXfCM3m/summerfield-336672-640-jpg.jpg"}
                	console.log(imgbb.size);
                	//thumb: {filename: "summerfield-336672-640-jpg.jpg", name: "summerfield-336672-640-jpg", mime: "image/jpeg", extension: "jpg", url: "https://i.ibb.co/yXZLwbV/summerfield-336672-640-jpg.jpg"}
                	console.log("imgbb.thumb.url : " +imgbb.thumb.url);
                	
                	
                	console.log(imgbb.time);
                	console.log(imgbb.title);
                	console.log(imgbb.url);
                	console.log(imgbb.url_viewer);
                	
                	
                	console.log("반환값");
                	//console.dir(json);            	
                    //var obj = JSON.parse(json);
            		
            	}

            }
        });
    }
</script>
</head>
<body>
<form enctype="multipart/form-data" id="ajaxFrom" method="post">
    <input type="file" id="ajaxFile"/>
   
    <input type="button" onClick="ajaxFileUpload();" value="업로드"/>
</form>
</body>
</html>

<!-- <a href="http://localhost/ajSecurity/imgbb/key" >http://localhost/ajSecurity/imgbb/key</a>
<br></br>
<a href="http://localhost/aj/imgbb/key" >http://localhost/aj/imgbb/key</a>

 -->

 

 

 

방법2)

async function uploadImageToImgbb(imageFile, apiKey, albumId) {
  const formData = new FormData();
  formData.append('image', imageFile);
  formData.append('key', apiKey);

  try {
    const response = await fetch('https://api.imgbb.com/1/upload', {
      method: 'POST',
      body: formData
    });

    const result = await response.json();

    if (result.success) {
      console.log('Image URL:', result.data.url);
      if (albumId) {
        // Album 관련 처리를 여기서 수행
        console.log(`Image added to album: ${albumId}`);
      }
    } else {
      console.error('Error uploading image:', result.error.message);
    }
  } catch (error) {
    console.error('Error uploading image:', error);
  }
}

// 사용 예제
const imageFile = document.querySelector('input[type="file"]').files[0];
const apiKey = 'your_imgbb_api_key_here';
const albumId = 'aaa';  // 이 부분은 imgbb API의 앨범 기능 지원 여부에 따라 처리

uploadImageToImgbb(imageFile, apiKey, albumId);

 

 

 

 

 

 

 

리액트 처리

 

//imgbb 업로드하기
async function imgbbUpload(imageData, fileName) {
  const formData = new FormData();
  formData.append("image", imageData);
  formData.append("key", ""); // Replace with your actual API key
  formData.append("name", fileName);

  const response=await fetch("https://api.imgbb.com/1/upload", {
    method: "POST",
    body: formData,
  });

  if(!response.ok){
    console.error("Upload failed");
    throw new Error("Upload failed");
  }

  const res = await response.json();
  return res.data.url;

}

 

 

 

 

function imageLoader(config) {
  const urlStart=config.src.split('upload/')[0];
  const urlEnd=config.src.split('upload/')[1];
  const transformations=`w_200,q_${config.quality}`;
  return `${urlStart}upload/${transformations}/${urlEnd}` ;
}


function Post({ post, action }) {
  return (
    <article className="post">
      <div className="post-image">
        <Image loader={imageLoader}   src={post.image} alt={post.title} fill    quality={50} />
        {/* <CldImage
            src={post.image}  width="100" height="100"  crop={{ type: 'auto', source: true }}
        />  */}

 

css

.post-image{
  position: relative;
  width: 8rem;
  height: 6rem;
  object-fit: cover;
}

 

다음을 참조

https://macaronics.net/m04/react/view/2239

 

 

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  라이트

암발생의 35%는 식생활(영양학적) 요인에 의한 것이며, 30%는 흡연, 3%는 음주, 7%는 성생활 및 생식(임신, 출산), 3%는 물리학적 요인, 10%는 감염, 4%는 직업이 암유발의 원인이다. - New Life 편집부

댓글 ( 5)

댓글 남기기

작성