본문 바로가기

트러블 슈팅

flask 서버에 이미지 올리기 고민

  • 문제점

flask서버에 이미지를 업로드 할려는 과정에서 어떻게 이미지를 올릴 수 있을까 고민을 해보았는데

찾아보니

2가지 방법이 있었다 한가지는 db에 이미지 자체를 올리는 방법

다른하나는 서버에 올리고 경로만 설정해주는 방법

  • 해결

후자가 전자보다 좋다는 것을 발견했다.

전자는 db의 용량문제, 속도문제가 발생한다는 단점이 있었다.

$(document).ready(function () {
            show();
        });
        function posting() {
            let title = $('#title').val()
            let content = $("#content").val()

            // 파일을 보내기 위한 코드
            let file = $('#file')[0].files[0] // id file의 0번째 태그의 files 중 0 번째 파일
            let form_data = new FormData()

            form_data.append("file_give", file)
            form_data.append("title_give", title)
            form_data.append("content_give", content)
            console.log(file)
            $.ajax({
                type: "POST",
                url: "/diary",
                data: form_data,
                // 파일을 보내는데 필요한 기본 세팅이 되어있지 않을 수 있기 떄문에 false로 설정
                cache: false,
                contentType: false,
                processData: false,
                success: function (response) {
                    alert(response["msg"])
                    window.location.reload()
                }
            });
        }
        function show(){
            $.ajax({
            type: "GET",
            url: "/test",
            data: {},
            success: function (response) {
                let rows = response['images']
                for(let i=0; i<rows.length; i++){
                    let image = rows[i]['file']
                    let temp_html = `<img src="/static/${image}" alt="이미지"/>`
                    $('#imageBox').append(temp_html)
                }
            }
        })
        }

먼저 이미지 파일을 flask에 보내기 위해서 ajax코드를 이용했다.

중요한것은 뒤에붙는 cache: false, contentType: false, processData: false, 이것 3가지를 넣어줘야 한다는것

cache는 파일을 올리게되면 데이터가 남아 다음파일이 안올라가는것을 방지하는것 같았다.

남은 두가지는 좀더 알아봐야겠다.

 

@app.route('/diary', methods=['POST'])
def save_diary ():
    title_receive = request.form['title_give']
    content_receive = request.form['content_give']

    # 파일 저장을 위한 부분
    file = request.files["file_give"]

    # 파일 확장자
    extension = file.filename.split('.')[-1]

    today = datetime.now()
    mytime = today.strftime('%Y-%m-%d-%H-%M-%S')

    filename = f'file-{mytime}'

    save_to = f'static/{filename}.{extension}'
    file.save(save_to)

    doc = {
        'title': title_receive,
        'content': content_receive,
        'file': f'{filename}.{extension}'
    }

    db.diary.insert_one(doc)
    return jsonify({'msg': '저장 완료!'})

flask에서 파일을 받게되면 먼저 파일 이름을 .으로 split해줘서 확장자를 만들고, 이름은 저장한 날짜,시간으로 만들었다.

그러고 나서 그파일을 static폴더에 저장함과 동시에 db에 이름을 저장했다.

서버에 app.py(여기서는 test.py), te mplates/index.html, static폴더를 저장하고 돌려본다.
잘 작동한다.