# ajax file upload

## jQuery ajax file upload

jQuery에서 파일 업로드를 하려면 다음과 같은 옵션 설정을 해야한다.

```javascript
$.ajax({
    //...
    processData:false,
    contentType:false,
    //...
});
```

### **processData**&#x20;

processData는 data를 쿼리 스트링으로 변환하도록 설정하는 옵션이다.

* true - data를 **application/x-www-form-urlencoded** 형식으로 변환
* false - data를 변환 처리하지 않음

### **contentType**&#x20;

contentType은 요청의 `Content-Type` 헤더를 정의한다. charset은 항상 **UTF-8**이다

* application/x-www-form-urlencoded
* multipart/form-data
* text/plain
* false

contentType을 **multipart/form-data** 또는 **false**로 설정해야 파일 전송이 가능하다.

## FormData

FormData는 **multipart/form-data** 방식에서도 사용할 수 있는 저장소이다. 이를 이용해 파일을 업로드하는 것이 가능하다. 다음과 같이 생성한다.

```javascript
const formData = new FormData();
```

전송할 데이터는 다음과 같이 추가한다.

```javascript
formData.append("key", value);
```

key는 파라미터 명이며 String 형태로 설정한다. value는 String 또는 Blob으로 설정한다.

## File Input에 선택된 파일 확인

File은 input 태그를 이용하여 선택할 수 있다.

```markup
<input type="file">
```

File이 선택되거나 취소되는 경우 **change** 이벤트가 발생한다.

```javascript
$("input[type=file]").change(function(){
    
});
```

File input에는 **`files`**&#xB77C;는 내장 속성이 존재하며 이를 사용하여 선택된 파일을 확인할 수 있다.

```javascript
$("input[type=file]").change(function(){
    console.log(this.files);
});
```

선택된 파일이 배열로 관리되기 때문에 파일 선택을 취소한 경우 length가 0이다. 따라서 다음과 같이 조건을 설정할 수 있다.

```javascript
if(this.files.length > 0){
    //파일이 선택된 경우
}
else {
    //파일이 선택 해제된 경우
}
```

파일이 선택된 경우 formData에 이를 담아 비동기로 전송하는 코드는 다음과 같다.

{% tabs %}
{% tab title="jQuery" %}

```javascript
$(".file-selector").change(function(){
    if(this.files.length > 0){
    
        const formData = new FormData();
    
        for(let i=0; i < this.files.length; i++){
            formData.append("attach", this.files[i]);
        }
        
        $.ajax({
            url:"서버의업로드주소",
            method:"post",
            contentType:false,
            processData:false,
            data:formData,
            success:function(resp){
                console.log("업로드 성공", resp);
            },
            error:function(){
                console.log("업로드 실패");
            }
        });
    }
});
```

{% endtab %}

{% tab title="HTML" %}

```html
<input type="file" class="file-selector" multiple>
```

{% endtab %}
{% endtabs %}

서버는 구현하지 않았으므로 업로드 주소는 생략하였으며 서버에서 반환하는 응답 정보는 success 함수의 resp에 전달된다. 파일의 개수와 관계없이 첨부된 경우 **attach** 라는 이름으로 서버에 전달된다.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sysout.co.kr/web/develop-page/js/jquery/ajax/ajax-file-upload.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
