Django實(shí)現(xiàn)圖片文字同時提交的方法
本文實(shí)例講述了Django實(shí)現(xiàn)圖片文字同時提交的方法。分享給大家供大家參考。具體分析如下:
jQuery為我們網(wǎng)站開發(fā)解決了很多問題,使我們的網(wǎng)站用戶體驗(yàn)大大的提高了。舉個簡單的例子,我們用AJAX技術(shù)來實(shí)現(xiàn)對表單的異步提交,使用戶在體驗(yàn)上有了很大的改觀,用戶在提交數(shù)據(jù)的同時還可以干一些其他的事情。
不過,今天在開發(fā)中遇到一個特別頭痛的問題,剛開始不知道,以為可以實(shí)現(xiàn),糾結(jié)了將近4個小時之久,但結(jié)果很是令人失望。
問題是這樣的:為了提高用戶體驗(yàn),我決定使用AJAX異步提交,于是我用jQuery的$.post去異步提交表單數(shù)據(jù),文本信息可以很輕松的提交,但是,卻怎么也無法提交圖片數(shù)據(jù)。怎么辦呢?
在網(wǎng)上查了很多資料,后來發(fā)現(xiàn)jQuery不支持圖片上傳(附件上傳),但是有相關(guān)的插件,于是我開始慢慢琢磨,開始用另一個專門上傳文件的插件jquery.ajaxfileupload.js,折騰了很久,總可以上傳圖片了。但是新的問題有產(chǎn)生了。
通過ajaxfileupload來異步上傳圖片的同時,卻不能提交文本數(shù)據(jù)。囧啊…….
在網(wǎng)上查了很多資料,折騰了許久,沒有Django開發(fā)的相關(guān)資料,怎么辦?自己想辦法…….
后來找到了解決方案,跟大家分享一下:
思路:
由于使用jquery.ajaxfileupload.js插件不能傳遞自定義的參數(shù),腫么辦?自己改寫插件唄。碰巧,網(wǎng)上有別人改過的現(xiàn)成代碼,二話不說,先拿來試試。以下即是我試驗(yàn)的過程。
1. 前臺頁面(部分代碼):
<table border="0" width="100%">
<form action="." method="post" id="annex_form_2"></form>
<tbody>
<tr>
<td class="col_name" nowrap="nowrap" width="26%">證書名稱:</td>
<td width="64%"><input size="65" class="input_general" id="prove_name_2" maxlength="50" name="prove_name"
type="text"></td>
<td nowrap="nowrap" width="7%"></td>
<td nowrap="nowrap" width="3%"><a href="javascript:void(0);" onclick="SubmitAnnexInfo(2)" title="保存"><img
src="/static/img/hr_manage/btn_save.gif" alt="點(diǎn)此保存"></a></td>
</tr>
<tr>
<td class="col_name">證件類型:</td>
<td><select id="prove_type_2" name="prove_type">
<option selected="selected" value="1">身份證</option>
<option value="2">學(xué)位證</option>
<option value="3">其他證</option>
</select></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td class="col_name">證書描述:</td>
<td><input size="80" class="input_general" id="prove_desc_2" maxlength="60" name="prove_desc" type="text"></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td class="col_name">附件地址:</td>
<td><input size="45" class="input_general" id="prove_url_2" maxlength="45" name="prove_url" style="border:0px;"
type="file"></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="4">
<hr>
</td>
</tr>
</tbody>
</table>
2. 更改后的jquery.ajaxfileupload.js:
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//增加文本參數(shù)的支持
if (data) {
for (var i in data) {
$('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, s.data);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
$(io).remove();
$(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
})
3. 調(diào)用方法
//保存附件信息
function SaveAnnexInfo() {
var prove_name = $("#id_prove_name").val(); //從界面得到值
var prove_type = $("#id_prove_type").val();
var prove_desc = $("#id_prove_desc").val();
$.ajaxFileUpload({
url: "/test/annex_info /", //請求的Url地址
secureuri:false,
fileElementId:'id_prove_url',
dataType: 'json',
data: { //加入的文本參數(shù)
"prove_name":prove_name,
"prove_type":prove_type,
"prove_desc":prove_desc
},
success: function(data) {
asyncbox.tips('操作成功!', 'success');
},
error: function() {
asyncbox.tips("上傳失敗,請檢查文件是否符合格式要求。");
}
});
}
4. Python后臺處理(代碼片段)
if annex_form.is_valid():
annex_info = annex_form.save(commit=False)
#獲取上傳
annex_url = request.FILES.get('prove_url','') #取附件
annex_info.entry = entry_info
annex_info.prove_url = annex_url
annex_info.save()
return HttpResponse(1) #操作成功
return HttpResponse(0) #操作失敗
希望本文所述對大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python 給DataFrame增加index行名和columns列名的實(shí)現(xiàn)方法
今天小編就為大家分享一篇python 給DataFrame增加index行名和columns列名的實(shí)現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
python使用matplotlib的savefig保存時圖片保存不完整的問題
這篇文章主要介紹了python使用matplotlib的savefig保存時圖片保存不完整的問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Python?OpenCV形態(tài)學(xué)運(yùn)算示例詳解
這篇文章主要為大家介紹了OpenCV中的幾個形態(tài)學(xué)運(yùn)算,例如:腐蝕&膨脹、開&閉運(yùn)算、梯度運(yùn)算、頂帽運(yùn)算黑帽運(yùn)算,感興趣的可以了解一下2022-04-04
提高python代碼可讀性利器pycodestyle使用詳解
鑒于 Python 在數(shù)據(jù)科學(xué)中的流行,我將深入研究 pycodestyle 的使用方法,以提高 Python 代碼的質(zhì)量和可讀性。如果你想提升代碼質(zhì)量,歡迎收藏學(xué)習(xí),有所收獲,點(diǎn)贊支持2021-11-11
利用PyQt中的QThread類實(shí)現(xiàn)多線程
本文主要給大家分享的是python實(shí)現(xiàn)多線程及線程間通信的簡單方法,非常的實(shí)用,有需要的小伙伴可以參考下2020-02-02
Django數(shù)據(jù)庫表反向生成實(shí)例解析
這篇文章主要介紹了Django數(shù)據(jù)庫表反向生成實(shí)例解析,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02
基于scrapy實(shí)現(xiàn)的簡單蜘蛛采集程序
這篇文章主要介紹了基于scrapy實(shí)現(xiàn)的簡單蜘蛛采集程序,實(shí)例分析了scrapy實(shí)現(xiàn)采集程序的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04

