Сожмите и загрузите изображение, используя python-flask

1

Я использую приложение Python-flask для обработки изображений, однако сжатие изображения выполняется в JavaScript, а затем загрузка выполняется в блэк-флэке python, когда я пытаюсь получить доступ к изображению в методе python с помощью request.args.get('image '), его указание Отсутствует, как указано ниже

var img = $('#img-upload')[0];
    function readURL(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function(e) {
          $('#img-upload').attr('src', e.target.result);
          img.onload = function() {
              alert("Image is loaded");
              var MAX_WIDTH = 100;
              var MAX_HEIGHT = 100;
              var width = img.width;
              var height = img.height;

              if (width > height) {
                if (width > MAX_WIDTH) {
                  height *= MAX_WIDTH / width;
                  width = MAX_WIDTH;
                }
              } else {
                if (height > MAX_HEIGHT) {
                  width *= MAX_HEIGHT / height;
                  height = MAX_HEIGHT;
                }
              }

              var canvas = document.createElement("canvas");
              canvas.width = width;
              canvas.height = height;
              canvas.getContext("2d").drawImage(this, 0, 0, width, height);
              var newImageData = canvas.toDataURL('image/png', 30/100);
              var result_image_obj = new Image();
              result_image_obj.src = newImageData;
              console.log(result_image_obj.src);
              console.log("Starting Upload...");

              if (result_image_obj.src == "") {
                  alert("You must load an image and compress it first!");
                  return false;
              }
              var callback= function(response){
                  console.log("image uploaded successfully! :)");
                  console.log(response);          
              }
              $.ajax({
                  url:"/users/api/v1/uploadimage",
                  type:'POST',
                  data:{'image':result_image_obj},
                  cache:false,
                  processData:false,
                  contentType:false,
                  error:function(){
                      console.log("upload error")
                  },
                  success:function(data){
                      console.log(data)
                      console.log("upload success")
                  }
              })
              console.log("Completed Upload...");
          }
        }
        reader.readAsDataURL(input.files[0]);
      }
    }

    $("#imgInp").change(function(){
        readURL(this);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" action="/updateuser" method="POST" enctype="multipart/form-data">
        <input type='file' id="imgInp"/>
        <img id="img-upload" name="img-upload" src="#"/>
</form>
Проблема Im сталкивается, я не могу получить изображение в колбе python через request.args.get, что я делаю неправильно? Pls предлагает. код python, как показано ниже
@app.route('/users/api/v1/uploadimage',methods=['GET','POST'])
def uploadimage():
    print "In uploadimage()"
    try:
        file = request.args.get('image')
        print "Filename",file
    except Exception as e:
        print str(e)
        return "True";
  • 0
    код состояния 400 - неверный запрос , 404 не найден - что вы получаете?
  • 0
    пожалуйста, посмотрите на этот flask.pocoo.org/docs/0.12/patterns/fileuploads
Показать ещё 4 комментария
Теги:
flask

2 ответа

2

Он работает для меня, чтобы сжать и загрузить изображение.

function readFile(evt) {
	    var file = evt.target.files[0];
	    var reader = new FileReader();
	    output_format = "jpg";
	    reader.onload = function(event) {
	        var i = document.getElementById("source_image");
	            i.src = event.target.result;
	            i.onload = function(){
	                image_width=$(i).width(),
	                image_height=$(i).height();

	                if(image_width > image_height){
	                    i.style.width="320px";
	                }else{
	                    i.style.height="300px";
	                }
	                i.style.display = "block";
	                console.log("Image loaded");
	            }
	    };

	    console.log("Filename:" + file.name);
	    console.log("Filesize:" + (parseInt(file.size) / 1024) + " Kb");
	    console.log("Type:" + file.type);
	    reader.readAsDataURL(file);

	    return false;
	}
 
 	$( "#upload" ).click(function() {
        var source_image = document.getElementById('source_image');
        if (source_image.src == "") {
            alert("You must load an image first!");
            return false;
        }

        var quality = 30;
       	
        console.log("process start...");
        var time_start = new Date().getTime();
        output_format = "jpg";
        console.log("process start compress ...");
	    source_image.src = jic.compress(source_image,quality,output_format).src;
	    console.log('Compressed in: ' + new Date().getTime() - time_start + 'ms');

	    var successCallback= function(response){
            console.log("image uploaded successfully! :)");
            console.log(response);       
        }

        var errorCallback= function(response){
            console.log("image Filed to upload! :)");
            console.log(response); 
        }
    	
    	var time_start = new Date().getTime();
    	console.log("process start upload ...");
    	jic.upload(source_image, '/uploadimage', 'file', 'new.jpg',successCallback,errorCallback);
    	console.log('uploaded in: ' + new Date().getTime() - time_start + 'ms');
    	
    });

document.getElementById('fileinput').addEventListener('change', readFile, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="upload_form" action="/updateuser" method="POST" enctype="multipart/form-data">
		<label for="file">Choose file</label>
		<input type="file" id="fileinput" />
		<img id="source_image">
		<input type="button" id="upload" value="uploadimage">
</form>
<script src="https://github.com/brunobar79/J-I-C/blob/master/src/JIC.js"></script>

Код Python

def uploadimage():
    print "In uploadimage() trying to upload"
    try:
        file = request.files['file']
        print "File",file
        print "Name",file.filename
    except Exception as e:
        print "Failed",str(e)
  • 0
    все сделано! Вы заслуживаете моего возражения
1

Okey, Позвольте мне исправить некоторые проблемы, которые я нашел с вашим кодом!

Во-первых, вам нужно использовать объект FormData из javascript для отправки байтов на сервер (сжатое изображение) в этом случае. для этого я добавил следующий код:

console.log("Starting Upload...");
var formData = new FormData();
formData.append("fileToUpload", result_image_obj.src);

и теперь вы можете легко отправить его через ajax:

$.ajax({
                  url:"/users/api/v1/uploadimage",
                  type:'POST',
                  data:formData,
                  processData: false, // important
                  contentType: false, // important
                  enctype: 'multipart/form-data',
                  error:function(){
                      console.log("upload error")
                  },
                  success:function(data){
                      console.log(data)
                      console.log("upload success")
                  }
              })

Обратите внимание: вам необходимо отправить объект formData в качестве параметра данных в вашем ajax и с помощью enctype: "multipart/form-data".

Теперь в вашем фляжном сервере используйте этот код:

@app.route('/users/api/v1/uploadimage', methods=['GET', 'POST'])
def uploadimage():
    """
    this will try to upload an image
    """
    print "In uploadimage()"
    try:
        a_file = request.get_data(cache=False, as_text=False, parse_form_data=False)
        print "Filename", a_file
    except Exception as exce:
        print str(exce)
        return "True"
    return "oke"

как сказано здесь, метод get_data

Это считывает буферизованные входящие данные от клиента в одну байтовую строку. По умолчанию это кэшируется, но это поведение можно изменить, установив кеш в False

теперь вторая проблема заключается в том, чтобы найти, как сохранить этот файл в виде строки на вашем сервере:

все еще глядя, как это сделать, добавит его в ближайшее время.

  • 0
    Хорошо, большое спасибо за помощь.
  • 0
    Это поможет вам решить что-то ??
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню