通过Ajax调整大小并上传图片

时间:2016-01-19 08:08:11

标签: javascript jquery ajax

我有这个代码调整图像大小,我想在调整照片大小后上传并使用Ajax提交表单。我试过这样做,但似乎没有调整我的照片大小。我是Javascript的新手,请指导我。以下是我的代码: -

<ListView.Resources>
    <!-- Better to put this to another XAML file -->
    <Style x:Key="ListViewItemStyleDefault" TargetType="ListViewItem">
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
        <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
        <Setter Property="TabNavigation" Value="Local"/>
        <Setter Property="IsHoldingEnabled" Value="True"/>
        <Setter Property="Padding" Value="12,0,12,0"/>
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="MinWidth" Value="{ThemeResource ListViewItemMinWidth}"/>
        <Setter Property="MinHeight" Value="{ThemeResource ListViewItemMinHeight}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListViewItem">
                    <ListViewItemPresenter CheckBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}" ContentMargin="{TemplateBinding Padding}" CheckMode="Inline" ContentTransitions="{TemplateBinding ContentTransitions}" CheckBoxBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}" DragForeground="{ThemeResource ListViewItemDragForegroundThemeBrush}" DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}" DragBackground="{ThemeResource ListViewItemDragBackgroundThemeBrush}" DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}" FocusBorderBrush="{ThemeResource SystemControlForegroundAltHighBrush}" FocusSecondaryBorderBrush="{ThemeResource SystemControlForegroundBaseHighBrush}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" PointerOverForeground="{ThemeResource SystemControlHighlightAltBaseHighBrush}" PressedBackground="{ThemeResource SystemControlHighlightListMediumBrush}" PlaceholderBackground="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" PointerOverBackground="{ThemeResource SystemControlHighlightListLowBrush}" ReorderHintOffset="{ThemeResource ListViewItemReorderHintThemeOffset}" SelectedPressedBackground="{ThemeResource SystemControlHighlightListAccentHighBrush}" SelectionCheckMarkVisualEnabled="True" SelectedForeground="{ThemeResource SystemControlHighlightAltBaseHighBrush}" SelectedPointerOverBackground="{ThemeResource SystemControlHighlightListAccentMediumBrush}" SelectedBackground="{ThemeResource SystemControlHighlightListAccentLowBrush}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style x:Key="ListViewItemStyleStretch" TargetType="ListViewItem" BasedOn="{StaticResource ListViewItemStyleDefault}">
        <!-- Magic here -->
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
    </Style>
</ListView.Resources>
<ListView.ItemContainerStyle>
    <StaticResource ResourceKey="ListViewItemStyleStretch"/>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
    <!-- Your ItemTemplate... -->
</ListView.ItemTemplate>

2 个答案:

答案 0 :(得分:1)

您无法使用新数据设置文件输入,用户必须出于安全原因选择文件。

为了上传生成的图像,您可以上传数据URL并将base64字符串解码回二进制格式并保存在服务器端。或者,您可以将画布中的图像作为blob获取,然后将其附加到FormData对象。

而不是调用toDataURL,您可以调用toBlob来获取blob对象。

canvas.toBlob(function(imgBlob){
   formData.append("receipt",imgBlob,"filenameForImage.png");
},'image/png');

请注意,toBlob方法尚未完全支持,但MDN参考确实提供了可以使用的polyfill:

  

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

if (!HTMLCanvasElement.prototype.toBlob) {
 Object.defineProperty(HTMLCanvasElement.prototype, toBlob, {
  value: function (callback, type, quality) {

    var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
        len = binStr.length,
        arr = new Uint8Array(len);

    for (var i=0; i<len; i++ ) {
     arr[i] = binStr.charCodeAt(i);
    }

    callback( new Blob( [arr], {type: type || 'image/png'} ) );
  }
 });
}

答案 1 :(得分:0)

你可以试试这个

<强> HTML

<form id="imgLocal" name="imgLocal" accept-charset="utf-8" enctype="multipart/form-data">
    <input type="file" name="receipt" id="receipt" accept="images/*" onchange="handleFiles();" />
</form>

<script>  

    function handleFiles()
    {

        var image= document.getElementById('receipt');

        var file = image.files[0];
        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onload = function(e) {
                    img.src = e.target.result;
                    img.onload = function () {
                            var canvas = document.createElement("canvas");
                            var ctx = canvas.getContext("2d");
                            ctx.drawImage(img, 0, 0);
                            var MAX_WIDTH = 400;
                            var MAX_HEIGHT = 300;
                            var width = this.width;
                            var height = this.height;
                            if (width > height) {
                                    if (width > MAX_WIDTH) {
                                            height *= MAX_WIDTH / width;
                                            width = MAX_WIDTH;
                                    }
                            } 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(img, 0, 0, width, height);
                            var dataurl = canvas.toDataURL("image/png");
                            upload(dataurl);
                    };
                    image.onerror= function() {
                            alert('Invalid file type: '+ file.type);
                    };
            }
            reader.readAsDataURL(file);
    }
}

function upload(file) {
                var form = new FormData();
                form.append('image', file);      
                $.ajax({
                      url: 'server.php',
                      data: form,
                      processData: false,
                      contentType: false,
                      type: 'POST',
                      success: function(data){
                        alert(data);
                      }
                 });
     }

</script>

服务器端:

<?php

$filename = "image_".uniqid().".png";
$dest = __DIR__.$filename;

$imgData = str_replace(' ','+',$_POST['image']);
$imgData =  substr($imgData,strpos($imgData,",")+1);
$imgData = base64_decode($imgData);

$file = fopen($dest, 'w');
fwrite($file, $imgData);
fclose($file);

?>

Check my blog