django上传图片和文字记录

时间:2023-12-19 11:12:50

直接上代码

html

               <form class="form-horizontal" id="upload-form">
<div class="col-md-6">
<div class="form-group">
<label class="col-sm-3 control-label">选择图片:</label> <div class="col-sm-9">
<input type="file" id = "picfile" name = "picfile">
</div>
</div>
<div class="btn-group btn-group-xl pull-right">
<button type="submit" class="btn btn-primary">提交</button>
</div>
</div>
</form>

jquery

$("#upload-form").submit( function() {
var checklist = $("input[name='checklist']");
var choice = new Array();
for (var i = 0; i < checklist.length; i++) {
if (checklist[i].checked) {
choice.push(checklist[i].value);
}
}
var imgs = $("#picfile")[0].files[0];
var data = new FormData();
data.append('taskids', choice)
data.append('imgs', imgs)
if (choice.length && imgs){
$.ajax({
type: 'POST',
url: '/rankkw/uploadPicture/',
data: data,
cache: false,
              async: false, 
processData: false,
contentType: false,
              success: function (data, status) {
            if (data.ret == 0) {
            alert('上传图片成功!');
            table.ajax.reload();
            }
            else {
            alert("上传图片失败!失败原因:" + data.message);
             }
              },
              error: function (data) {
             alert( "错误原因"+data);
              }
        }) }else{ alert("未选中任务或未选择图片!") } })

后台

def uploadPicture(request):
try:
taskids = request.POST.get('taskids')
if not taskids:
ex = u"任务id获取失败"
raise Exception, ex
reqfile = request.FILES.get('imgs')
img = Image.open(reqfile)
img.thumbnail((500,500), Image.ANTIALIAS)
img.save('D:\\django\\amzkeyword\\statics\\uploadimgs\\1.png', "png")
return render_to_response("addtask.html", { "upload_msg": u"上传成功"})
except Exception, e:
err = u"上传失败,错误原因:" + str(e)
return render_to_response('addtask.html', { "upload_msg": err})