#javascript #c# #asp.net-core #file-upload #html-input
Вопрос:
Я попытался выполнить захват ввода Html5 с камеры(Samsung Tab s7), а затем изменить размер(моя главная цель на данный момент-уменьшить размер изображения), а затем загрузить метод публикации через мой контроллер. Но когда я загружаю, мой файл распознается как .bin и сохраняется вот так. Я не сохраню jpeg. Как я могу это решить?
HTML :
<input type="file" id="captureImageInput" style="display:none;" accept="image/*" capture>
JS :
const fileInput = document.getElementById('captureImageInput');
fileInput.addEventListener('change', e => {
if (e.target.files.length == 0) {
// No file captured, ignore
return;
}
else{
var imageFile = e.target.files[0];
//--resize image START
var canvas = document.createElement("canvas");
var img1 = document.createElement("img");
img1.setAttribute('src', imageFile);
var ctx = canvas.getContext("2d");
ctx.drawImage(img1, 0, 0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img1.width;
var height = img1.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
}
else if (width == 0 amp;amp; height == 0)
{
width = MAX_WIDTH;
height = MAX_HEIGHT;
}
else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img1, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/jpeg");
var blobBin = atob(dataurl.split(',')[1]);
var array = [];
for (var i = 0; i < blobBin.length; i ) {
array.push(blobBin.charCodeAt(i));
}
var resizedFileBlob = new Blob([new Uint8Array(array)], { type: 'image/jpeg' });
//--resize image END
var fullFileName = serialNo "-" stockNo;
var fileImage = new File([resizedFileBlob], fullFileName);
var myFormData = new FormData();
myFormData.append('FormFile', fileImage);
$.ajax({
//POST OPERATION TO CONTROLLER
});
}
});
Сторона контроллера:
[HttpPost]
public JsonResult SavePhysicalPath(FileModel myFormData)
{
//update physical path operatıons..
}
Класс файловой модели:
public class FileModel
{
public string FileFolderPath { get; set; }
public string Files { get; set; }
public IFormFile[] FormFile { get; set; }
}
Ответ №1:
Согласно вашим кодам, я думаю, что проблема связана с тем, что вы создали новый файл с помощью этой строки var fileImage = new File([resizedFileBlob], fullFileName);
.
Я предлагаю вам удалить эту строку и напрямую использовать ее в resizedFileBlob
качестве параметра и передать на серверную часть.
Я создал тестовую демонстрацию, как показано ниже, и вы можете обратиться к ней.
JS:
<script type="text/javascript">
$(document).ready(function () {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function () {
// set size proportional to image
canvas.height = canvas.width * (img.height / img.width);
// step 1 - resize to 50%
var oc = document.createElement('canvas'),
octx = oc.getContext('2d');
oc.width = img.width * 0.5;
oc.height = img.height * 0.5;
octx.drawImage(img, 0, 0, oc.width, oc.height);
// step 2
octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);
// step 3, resize to final size
ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5,
0, 0, canvas.width, canvas.height);
}
img.src = "https://i.imgur.com/SHo6Fub.jpg";
var cav = document.getElementById("canvas");
const file = dataURLtoBlob(cav.toDataURL());
var fileImage = new File([file], "test");
const fd = new FormData;
fd.append('image', fileImage);
$.ajax({
type: 'POST',
url: '/api/Foo',
data: fd,
processData: false,
contentType: false
});
});
function dataURLtoBlob(dataURL) {
let array, binary, i, len;
binary = atob(dataURL.split(',')[1]);
array = [];
i = 0;
len = binary.length;
while (i < len) {
array.push(binary.charCodeAt(i));
i ;
}
return new Blob([new Uint8Array(array)], {
type: 'image/png'
});
};
</script>
Вид:
<img src="https://i.imgur.com/SHo6Fub.jpg" width="300" height="234">
<canvas id="canvas" width=300></canvas>
Результат: