Web screenshot paste Upload

Source: Internet
Author: User

Web page paste Upload

In the production operation question and answer platform, there is a functional requirement is to allow users to ask questions or answers directly then paste in the edit box, and then submit. In the development of the front-end I use the Uikit, but uikit inside the HTMLEditor plugin on the image upload support is too poor, had to give up. I went to another page edit control, but found that these controls to handle the picture is to choose a network slice or upload from the local, which is good for publishing blog and so on, but for the users of the question and answer platform I do, they are more than just a brief description of the needs of the supervisor or others to answer questions, There is almost no requirement for the format, so the simpler the more convenient the better.

Refer to the practice, found that it is pasted immediately after the upload of pictures, so there will be a problem, once the user cancels the operation if not in the background to the uploaded image data to do the deletion will produce a lot of garbage data, and in the background to do records, rather than put the problem to the front to solve the simple, So using HTML5 's formdata to think of a solution:

    1. When the user pastes, the src attribute of the picture data and the created IMG element is saved to two arrays Datasarray and Urlsarray, associated with the subscript index.
    2. When the user clicks on the submission to obtain the content that the user edits, iterates through the Urlsarray each element Src_url, if src_url in the content, then replaces the Src_url in the content with uploadfile_i, I means src_ The index of the URL in Urlsarray, and then adds a (Uploadfile_i,datasarray[i]) key-value pair in the Formdata.
    3. After you save the picture data Datasarray[i] in the background, the path is a URL and the uploadfile_i in content is replaced with a URL.
    4. If the content is updated, the previous picture link Preurl is recorded before the data is updated in the background, and the picture is deleted if Preurl is not in the currently submitted content.

The front-end code is as follows:

varImagedatas2upload =New Array();varImageurls2upload =New Array();/* Read the picture data from the Clipboard, create an IMG element attached to the specified element, and save the image BLOB data and the IMG src attribute in the array */ function readimgfromclipboard(clipboarddata, Containerid){    vari =0, items, item, types;if(Clipboarddata) {items = Clipboarddata.items;if(!items) {return; }//Get data typeitem = items[0]; Types = Clipboarddata.types | | []; for(; i < types.length; i++) {if(Types[i] = = =' Files '{item = Items[i]; Break; }        }//Determine if it is a picture type        if(item && Item.kind = = =' file '&& Item.type.match (/^image\//i) ){//Read binary picture data            varBlob = Item.getasfile ();if(BLOB) {varReader =NewFileReader (); Reader.onload = function(e){                    //Append img element to specified element                    varIMG =NewImage ();                    IMG.SRC = E.target.result; $("#"+containerid). Append (IMG);//Save BLOB data and SRC attribute values to arrayImagedatas2upload.push (BLOB);                Imageurls2upload.push (IMG.SRC);                };            Reader.readasdataurl (BLOB); }        }    }}
 function csl_newqes(title, detail, topics, callback){    varc =NewFormData; C.append ("via","XHR2");//Replace the SRC attribute value of the IMG with a placeholder and add (placeholder, data) key-value pairs to the Formdata     for(varI=0; i<imageurls2upload.length;i++) {if(Detail.indexof (Imageurls2upload[i]) >=0){varfilename =' Upload_file_ '+ i;            Detail = Detail.replace (imageurls2upload[i],filename);        C.append (filename, imagedatas2upload[i],filename); }} c.append ("Detail", detail);//Erase dataImageurls2upload = []; Imagedatas2upload = [];if(Topicsinstanceof Array) {topics = Topics.join (); } c.append ("Topics", topics); C.append ("title", title);varSuccess_callback = Callback | | function(){}; $.ajax ({URL:'/create-question/', type:' POST ', Data:c, ProcessData:false,//Tell jquery not to convert data automaticallyContentType:false,//Tell jquery not to set the Content-type request headerDataType:' JSON ', Success: function(data){            if(data.success)            {success_callback (data); }Else{_alerterrorresponse (data.message); }}, Error: function(XHR, ts){            varmsg = ts +': '+ Xhr.statustext;        _alerterrorresponse (msg); }    });}

The Django Daemon code is as follows:

@login_required def create_question(Request):result = {' Success ':1,' message ':"',' qid ':None}Try: title = Request. post[' title '] Detail = Request. post[' Detail '] topics = Request. post[' Topics '].split (', ')#读取图片数据保存, replace the picture link placeholder with a real linkHS = Haystack (tags= (' Qimages ',), Root=settings. Media_root) forFninchRequest. files:img = Request. Files.get (FN,None) file_name ='%s.jpeg '% str (UUID.UUID1 ()) Hs.save (file_name, Img.read ()) URL = _qa_image_url_prefix + file_name Detail = re.sub (Re.compile (FN), url, detail) Username = Request.user.username QEs = Question (). Settitle (Tit Le). Setdetail (detail). Setasker (username) forTidinchTopicsifTid andTid not inchQes.topics:qes.topics.append (TID) result[' qid '] = Qes.save ()exceptException asex:result[' Success '] =0result[' message '] =' ERROR:%s. '% STR (ex)returnJsonresponse (Result)

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Web page paste Upload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.