使用ASP.net和jquery进行拖放

本文关键字:拖放 jquery ASP net 使用 | 更新日期: 2023-09-27 18:08:40

我尝试为头像图像创建一个拖放功能。我想要有人拖进盒子里的文件;上传到目录:'/images/profile/$username'

这是我的代码:

<div class='fileDrop'>
    <span id='fileDropTarget'>Drag your files here</span>
</div>
<script>
    function fileSetUploadPercent(percent) {
        var uploadString = "Uploaded " + percent + " %";
        $('#fileDropTarget').text(uploadString);
    }
    function fileUploadStarted(index, file, files_count) {
        fileSetUploadPercent(0); //set the upload status to be 0
    }
    function fileUploadUpdate(index, file, currentProgress) {
        var string = "index = " + index + " Uploading file " + file.fileName + " size is " + file.fileSize + " Progress = " + currentProgress;
        $('#status').text(string);
        fileSetUploadPercent(currentProgress);
    }
    function fileUploadFinished(index, file, json, timeDiff) {
        fileSetUploadPercent(100);
        $('#fileDropTarget').css('border', '2px dotted #000000').text("Upload Voltooid");
    }
    function fileDragLeave(event) {
        $('#fileDropTarget').css('border', '2px dotted #000000').text("Sleep uw foto hierin");
    }
    function fileDragOver(event) {
        $('#fileDropTarget').css('border', '2px dashed #000000').text("Sleep uw foto hierin");
    }
    $(".fileDrop").filedrop({
        fallback_id: 'fallbackFileDrop',
        url: '/controls/upload.ascx',
        allowedfiletypes: ['image/jpeg', 'image/png', 'image/gif'],   // filetypes allowed by Content-Type.  Empty array means no restrictions
        allowedfileextensions: ['.jpg', '.jpeg', '.png', '.gif'], // file extensions allowed. Empty array means no restrictions
        //    refresh: 1000,
        paramname: 'fileUpload',        // POST parameter name used on serverside to reference file, can also be a function taking the filename and returning the paramname
        maxfiles: 1,                    // Ignored if queuefiles is set > 0
        maxfilesize: 10,                // MB file size limit
        //    queuefiles: 0,            // Max files before queueing (for large volume uploads)
        //    queuewait: 200,           // Queue wait time if full
        //    data: {},
        //    headers: {},
        //    drop: empty,
        //    dragEnter: empty,
        dragOver: fileDragOver,
        dragLeave: fileDragLeave,
        //  docEnter: empty,
        //  docOver: fileDocOver,
        //  docLeave: fileDocLeave,
        //  beforeEach: empty,
        //  afterAll: empty,
        //  rename: empty,
        error: function (err, file) {
            switch (err) {
                case 'BrowserNotSupported':
                    $('#fileDropTarget').css('border', '2px dashed #FF0000').text('Uw browser wordt niet gesupport');
                    break;
                case 'TooManyFiles':
                    $('#fileDropTarget').css('border', '2px dashed #FF0000').text('U kunt maar 1 foto tegelijk uploaden');
                    break;
                case 'FileTooLarge':
                    $('#fileDropTarget').css('border', '2px dashed #FF0000').text('Uw foto is groter dan 10MB');
                    break;
                case 'FileTypeNotAllowed':
                    $('#fileDropTarget').css('border', '2px dashed #FF0000').text('Alleen fotos zijn toegestaan');
                    break;
                case 'FileExtensionNotAllowed':
                    $('#fileDropTarget').css('border', '2px dashed #FF0000').text('Alleen fotos zijn toegestaan');
                    break;
                default:
                    $('#fileDropTarget').css('border', '2px dashed #FF0000').text(err);
                    break;
            }
        },
        uploadStarted: fileUploadStarted,
        uploadFinished: fileUploadFinished,
        progressUpdated: fileUploadUpdate
    });
</script>

但是每次我尝试上传文件;我得到错误:'Not Found'。另一个问题是,我想用asp.net控件和POST请求上传这些文件。我不知道如何添加一个文件到FileUploadControl;我不知道如何从上传控件的dragfield中获取文件。

    protected void Page_Load(object sender, EventArgs e)
    {
        string filetype = Request.QueryString["fileType"];
        string filename = Request.QueryString["fileUpload"];
        FileUpload FileUploadControl = new FileUpload();
        string location = "~/upload";
        try
        {
            if (filetype == "avatar") location = "images/profile/";
            FileUploadControl.SaveAs(Server.MapPath("~/") + location + filename);
            LabelStatus.Text = "Upload status: File uploaded!";
        }
        catch (Exception ex)
        {
            LabelStatus.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }

提前谢谢。

使用ASP.net和jquery进行拖放

试试这个

HTML

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Upload.aspx.cs" Inherits="upload.Upload" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <style>
   body { padding:10px; font:14px/18px Calibri }
   .bold { font-weight:bold }
   td { padding:5px; border:1px solid #999 }
   p, output { margin:10px 0 0 0 }
   #drop_zone 
   { 
       margin:10px 0;
       width:40%; 
       min-height:150px; 
       text-align:center;
       text-transform:uppercase;
       font-weight:bold;
       border:8px dashed #898;
                height: 160px;
            }
  </style>
    <title></title>
    <script>
        var files;
        function handleDragOver(event) {
            event.stopPropagation();
            event.preventDefault();
            var dropZone = document.getElementById('drop_zone');
            dropZone.innerHTML = "Drop now";
        }
        function handleDnDFileSelect(event) {
            event.stopPropagation();
            event.preventDefault();
            /* Read the list of all the selected files. */
             files = event.dataTransfer.files;
            /* Consolidate the output element. */
             var form = document.getElementById('form1');
             var data = new FormData(form);
             for (var i = 0; i < files.length; i++) {
                 data.append(files[i].name, files[i]);
             }
             var xhr = new XMLHttpRequest();
             xhr.onreadystatechange = function () {
                 if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText) {
                     alert("upload done!");
                 } else {
                     //alert("upload failed!");
                 }
             };
             xhr.open('POST', "Upload.aspx");
            // xhr.setRequestHeader("Content-type", "multipart/form-data");
             xhr.send(data);
        }
  </script>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
        <br />
        <div id="drop_zone">Drop files here</div>
</form>
</body>
    <script>
        if (window.File && window.FileList && window.FileReader) {
            /************************************ 
             * All the File APIs are supported. * 
             * Entire code goes here.           *
             ************************************/

            /* Setup the Drag-n-Drop listeners. */
            var dropZone = document.getElementById('drop_zone');
            dropZone.addEventListener('dragover', handleDragOver, false);
            dropZone.addEventListener('drop', handleDnDFileSelect, false);
        }
        else {
            alert('Sorry! this browser does not support HTML5 File APIs.');
        }
  </script>
</html>
服务器端(Upload.aspx.cs)

using System;
using System.IO;
using System.Web;
namespace upload
{
    public partial class Upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
         if (IsPostBack)
         {
             UploadFile(sender,e);
         }
        }
        protected void UploadFile(object sender, EventArgs e)
        {
            HttpFileCollection fileCollection = Request.Files;
            for (int i = 0; i < fileCollection.Count; i++)
            {
                HttpPostedFile upload = fileCollection[i];
                string filename ="c:''Test''" +  Path.GetRandomFileName();
                upload.SaveAs(filename);
            }
        }
    }
}

试试这个

function sendFileToServer(formData, status) {
         var uploadURL = "FileUploadHandler.ashx"; //Upload URL
         var extraData = {}; //Extra Data.
         var jqXHR = $.ajax({
             xhr: function () {
                 var xhrobj = $.ajaxSettings.xhr();
                 if (xhrobj.upload) {
                     xhrobj.upload.addEventListener('progress', function (event) {
                         var percent = 0;
                         var position = event.loaded || event.position;
                         var total = event.total;
                         if (event.lengthComputable) {
                             percent = Math.ceil(position / total * 100);
                         }
                         //Set progress
                         status.setProgress(percent);
                     }, false);
                 }
                 return xhrobj;
             },
             url: uploadURL,
             type: "POST",
             contentType: false,
             processData: false,
             cache: false,
             data: formData,
             success: function (data, textStatus, jqXHR) {
                 status.setProgress(100);
             },
             complete: function (data,textStatus, jqXHR) {
                 $('.status').html(data.responseText).fadeIn().fadeOut(1600);
             }
         });
         status.setAbort(jqXHR);
     }
     var rowCount = 0;
     function createStatusbar(obj) {
         rowCount++;
         var row = "odd";
         if (rowCount % 2 == 0) row = "even";
         this.statusbar = $("<div class='statusbar " + row + "'></div>");
         this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
         this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
         this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
         this.abort = $("<div class='cancel'>cancel</div>").appendTo(this.statusbar);
         obj.after(this.statusbar);
         this.setFileNameSize = function (name, size) {
             var sizeStr = "";
             var sizeKB = size / 1024;
             if (parseInt(sizeKB) > 1024) {
                 var sizeMB = sizeKB / 1024;
                 sizeStr = sizeMB.toFixed(2) + " MB";
             }
             else {
                 sizeStr = sizeKB.toFixed(2) + " KB";
             }
             this.filename.html(name);
             this.size.html(sizeStr);
         }
         this.setProgress = function (progress) {
             var progressBarWidth = progress * this.progressBar.width() / 100;
             this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "%&nbsp;");
             if (parseInt(progress) >= 100) {
                 this.abort.hide();
             }
         }
         this.setAbort = function (jqxhr) {
             var sb = this.statusbar;
             this.abort.click(function () {
                 jqxhr.abort();
                 sb.hide();
             });
         }
     }
     function handleFileUpload(files, obj) {
         for (var i = 0; i < files.length; i++) {
             var fd = new FormData();
             fd.append('file', files[i]);
             var status = new createStatusbar(obj); //Using this we can set progress.
             status.setFileNameSize(files[i].name, files[i].size);
             sendFileToServer(fd, status);
         }
     }
     $(document).ready(function () {
         var obj = $("#dragandrop");
         obj.on('dragenter', function (e) {
             e.stopPropagation();
             e.preventDefault();
             $(this).css('border', '2px solid #0B85A1');
         });
         obj.on('dragover', function (e) {
             e.stopPropagation();
             e.preventDefault();
         });
         obj.on('drop', function (e) {
             $(this).css('border', '2px dotted #0B85A1');
             e.preventDefault();
             var files = e.originalEvent.dataTransfer.files;
             //We need to send dropped files to Server
             handleFileUpload(files, obj);
         });
         $(document).on('dragenter', function (e) {
             e.stopPropagation();
             e.preventDefault();
         });
         $(document).on('dragover', function (e) {
             e.stopPropagation();
             e.preventDefault();
             obj.css('border', '2px dotted #0B85A1');
         });
         $(document).on('drop', function (e) {
             e.stopPropagation();
             e.preventDefault();
         });
     });