之前没写过上传图片,现在两个项目都被我遇到了上传图片,上网找了好多,终于解决了。
我参考很多,但是其他网址找不到了,只记得这一个,参考:Ajax实现单图片上传,多图片上传,以及和对象的综合上传
接下来写一下我自己总结的代码(我是根据项目需求总结的,不需要照搬
):
〻 css不重要
.imagePreview {
width: 200px;
height: 180px;
background-position: center center;
/* background:url(http://cliquecities.com/assets/no-image-e3699ae23f866f6cbdf8ba2443ee5c4e.jpg); */
background-color:#fff;
background-size: cover;
background-repeat:no-repeat;
display: inline-block;
box-shadow:0px -3px 6px 2px rgba(0,0,0,0.2);
}
.imgUp
{
margin-bottom:15px;
}
.del
{
position:absolute;
top:0px;
height:30px;
text-align:center;
line-height:30px;
background-color:rgba(255,255,255,0.6);
cursor:pointer;
border: 0;
left: 215px;
}
.imgAdd
{
width:30px;
height:30px;
border-radius:50%;
background-color:#4bd7ef;
color:#fff;
box-shadow:0px 0px 2px 1px rgba(0,0,0,0.2);
text-align:center;
line-height:30px;
margin-top:0px;
cursor:pointer;
font-size:15px;
}
〻 html(如果是submit应该直接提交就可以吧,我没试)
<!-- enctype="multipart/form-data"必须写 -->
<form id="knowAddForm" name="knowAddForm" enctype="multipart/form-data">
<!-- {% csrf_token %} 因为不是直接submit,所以不用写,仅限django-->
<input type="text" id="userId" name="userId" placeholder="">
<div id='card-body-add' class="row mt-4">
<div class="col-lg-4 imgUp">
<div class="imagePreview"></div>
<label class="btn btn-info" style="top: 6px;">Upload
<!-- accept="image/gif,image/jpeg,image/jpg,image/png"只能选择图片 -->
<!-- multiple 支持多张图片 -->
<input type="file" name="imagesAdd" class="uploadFile_img_add" accept="image/gif,image/jpeg,image/jpg,image/png" style="width: 0px; height: 0px; overflow: hidden;" multiple>
</label>
<i class="fa fa-times del"></i>
</div>
<i class="fa fa-plus imgAdd"></i>
</div>
<button type="button" id="addOKButton">OK</button>
</form>
〻 js添加或删除div(这是我自己项目需要,不用关注)
//添加div
$(".imgAdd").click(function(){
count_add = $('#card-body-add .imgUp').length;
if (count_add < 3) {
$(this).closest(".row").find('.imgAdd').before('<div class="col-lg-4 imgUp"><div class="imagePreview"></div><label class="btn btn-info" style="top:6px;">Upload<input type="file" name="imagesAdd" class="uploadFile_img_add" accept="image/gif,image/jpeg,image/jpg,image/png" style="width:0px;height:0px;overflow:hidden;" multiple></label><i class="fa fa-times del"></i></div>');
}else{
alert('最多可上传3张照片');
}
});
//删除div
$(document).on("click", "i.del" , function() {
$(this).parent().remove();
});
〻 js选择的图片在页面显示
$(function() {
$(document).on("change",".uploadFile_img_add", function(){
var uploadFile = $(this);
var files = this.files ;
if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){
if (files[0].size >= 5242880){
return alert( '图片最大上传5MB。请重新选择');
}
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(files[0]); // read the local file
reader.onloadend = function(){
var image = new Image();
image.height = 180;
image.width = 200;
image.title = files.name;
image.name = "image_path_add";
image.src = this.result;
uploadFile.closest(".imgUp").find('.imagePreview').empty();//确保div里最多放一张图片
uploadFile.closest(".imgUp").find('.imagePreview').append(image);
}
}
});
});
〻 ajax上传图片(重要)
$('#addOKButton').click(function(){
var formData=new FormData();
//因为我需要多次上传多张照片,所以这样做(有好的建议可以提出来哦,我只会这种笨办法),普通的参照上面链接
imgCount = $('.uploadFile_img_add').length
//因为我最多能上传3张照片,所以做3次判断
for (var i=0;i<imgCount;i++){
if(i == 0){
formData.append("imgFiles_add",$('.uploadFile_img_add')[0].files[0])
}
if(i == 1){
formData.append("imgFiles_add",$('.uploadFile_img_add')[1].files[0])
}
if(i == 2){
formData.append("imgFiles_add",$('.uploadFile_img_add')[2].files[0])
}
}
var userId=$("#knowAddForm #userId").val();
formData.append("userId",userId);
$.ajax({
type: "POST",
url: '/user_add/',
dataType:"json",
data:formData,
async: false,
cache: false,
contentType: false, //禁止设置请求类型
processData: false, //禁止jquery对DAta数据的处理,默认会处理
headers: {
"X-CSRFToken": getCookie("csrftoken")
},//python专用的可能是,具体方法如何写请参考之前的文章
success: function (result) {
alert("成功");
},
error : function() {
alert("error!");
}
});
});
〻 django后台接收(重要)
from django.http import HttpResponse
import os.path
import shutil
from django.core.files.storage import FileSystemStorage
def knowledgeDetail_add(request):
if request.method == 'POST':
userId= request.POST.get('userId')
#django接收前台传过来的照片
image = request.FILES.getlist('imgFiles_add')
path_name = '/var/usr/images/'
upload_img = []
num = 1
#shutil.rmtree函数可用于递归删除目录中包含的文件和子目录。
if os.path.exists(path_name):
shutil.rmtree(path_name)
for i in range(0, len(image)):
upload_img.append(image[i])
#将图片写到指定路径下,并修改文件名称
for f in upload_img:
upload_img_name = 'img_' + str(userId) + '_'+ str(num) + '.jpg'
file = FileSystemStorage(location= path_name)
file_name = file.save(upload_img_name, f)
image_file_path = image_file_path + path_name + upload_img_name + ';'
num = num + 1
return HttpResponse(image_file_path)
以上,如果有不对的地方,欢迎一起探讨