我具有以下形式,该形式由我需要发送到服务器的两个字段组成:
所以我在这里要做的是将修改后的图像上传以及描述文本字段提交到同一服务器url。但是,修改后的图像总是先通过Ajax表单提交给服务器,而不捕获描述文本字段,之后再通过文本字段和原始图像上传再次提交实际的表单,而我不希望这样做。
我希望表单将修改后的图像上载字段与文本描述字段一起提交,因为它们应该存储在数据库中。
$('input:file').on('change', function(e) {
// Function to upload
let canvas;
let array_WH = new Array();
let percent = 50;
let img = new Image();
let cv;
var fileReader = new FileReader();
fileReader.onload = function(e) {
img.onload = function() {
array_WH = ff(img.height, img.width, percent); //Pavel: changed order to correct
console.log('old width: ' + img.width);
console.log('new width: ' + array_WH[0]);
width = array_WH[0];
height = array_WH[1];
if (canvas) return;
canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(this, 0, 0, width, height);
// //Line added
//var canvasData = canvas.toDataURL(); //Pavel: also for png can be: toDataURL("image/png");
var canvasData = canvas.toDataURL('image/jpeg', 0.5); //Pavel: sec param is quality from 0 to 1
cv = canvasData;
// //Line edited
console.log(this);
this.src = canvasData;
var url = "/Document/test/";
// alert(canvasData);
var image = canvasData;
var base64ImageContent = image.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
var blob = base64ToBlob(base64ImageContent, 'image/png');
var formData = new FormData();
formData.append('file', blob);
// $.ajax({
// url: url,
// type: "POST",
// cache: false,
// contentType: false,
// processData: false,
// data: formData})
// .done(function(e){
// alert('done!');
// });
// //Line added
console.log(canvasData.length * 3 / 4, ' bytes');
document.body.appendChild(this); //remove this if you don't want to show it
}
img.id = "image_resized";
img.src = e.target.result;;
}
fileReader.readAsDataURL(e.target.files[0]);
});
$('form').on('submit', function() {
oData = new FormData($('form#PostAttachment'));
oData.append('CustomField', 'This is some extra data');
var cv = $('img#image_resized').attr('src');
alert(cv);
var base64ImageContent = cv.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
var blob = base64ToBlob(base64ImageContent, 'image/png');
oData.append('file', blob);
var url = "/Document/test/";
$.ajax({
url: url,
type: "POST",
cache: false,
contentType: false,
processData: false,
data: oData
})
.done(function(e) {
alert('done!');
});
})
$('#submit').click(function() {
$('form').trigger('submit');
});
function ff(height, width, percentage) {
var newHeight = height * (percentage / 100);
var newWidth = width * (percentage / 100);
return [newWidth, newHeight];
}
function base64ToBlob(base64, mime) {
mime = mime || '';
var sliceSize = 1024;
var byteChars = window.atob(base64);
var byteArrays = [];
for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
var slice = byteChars.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {
type: mime
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div id="Main">
<form action="/Document/test/" method="POST" enctype="multipart/form-data" id="PostAttachment">
<div class="form-group">
<label class="col-xs-2 control-label" for="Description">
Desctiption <span style="color:#d38e99">*</span>
</label>
<div class="col-xs-10">
<input id="Description" name="description" class="form-control" value="">
</div>
</div>
<div class="form-group">
<label for="file" class="col-xs-2 control-label">Browse File (png , jpeg , jpg , gif , pdf , doc , docx , xls , xlsx) <span style="color:#d38e99">*</span></label>
<div class="col-xs-10">
<input id="BrowseFile" type="file" name="file" class="form-control">
<div style="float: left;margin: 5px;margin-left: 10px">Maximum Size: (5 MB)</div>
</div>
</div>
</form>
<input type="button" class="form-control" id="submit" name="submit" value="upload">
</div>
在服务器端,我使用python脚本获取提交的字段并将其存储,视图如下:
@app.route('/Document/test/',methods=['POST','GET'])
def test_upload():
if request.method=='POST':
description = request.form.get('description')
file = request.files.get('file')
AttachmentFolder = '/app/static/attachment/'
print "description is ",description
print "file is ",file
file.save(os.path.join(AttachmentFolder, secure_filename(file.filename)))
return render_template('customer/document1.html')
如上所述,如何获取修改后的图像以及描述文本字段(已提交到相同的url)?谢谢。