关于ajax文件上传的WebKitFormBoundary

时间:2015-09-08 15:57:34

标签: c# jquery ajax

我在通过ajax上传文件时遇到了一些麻烦。每当我尝试上传时,会附加额外的行,这些行在保存时会损坏文件。喜欢这个

 ------WebKitFormBoundaryR4wrAzWF9BYdge12
Content-Disposition: form-data; name="files"; filename="testing - Copy.txt"
Content-Type: text/plain

this is a test
------WebKitFormBoundaryR4wrAzWF9BYdge12--

这是我的HTML

var formData = new FormData();
formData.append("files", files[x], files[x].name);
var tempUrl = url + "&filename=" + files[x].name;
console.log(tempUrl, formData);

$.ajax({
    url: tempUrl,
    type: "Post",
    data: formData,
    processData: false,
    contentType: false,//"multipart/form-data",
    success: function () {
        console.log("done!")
    }});

这里是C#后端。我没有写这篇文章,而且我对C#不是很有经验,很抱歉,如果我错过了一个简单的解决方法。

public void ProcessRequest(HttpContext context, string tenant, string userId, int parentId)
{
    try
    {
        string filename = context.Request.QueryString["filename"];
        bool complete = string.IsNullOrEmpty(context.Request.QueryString["Complete"]) ? true : bool.Parse(context.Request.QueryString["Complete"]);
        bool getBytes = string.IsNullOrEmpty(context.Request.QueryString["GetBytes"]) ? false : bool.Parse(context.Request.QueryString["GetBytes"]);
        long startByte = string.IsNullOrEmpty(context.Request.QueryString["StartByte"]) ? 0 : long.Parse(context.Request.QueryString["StartByte"]); ;

        if (getBytes)
        {
            context.Response.Write("0");
            context.Response.Flush();
            return;
        }
        else
        {
            int fileSize = (int)context.Request.InputStream.Length;
            StructureManager manager = new StructureManager();

            string fileType = filename.Substring(filename.LastIndexOf("."));
            AcxiomPortal.SharedObjects.PortalService.File file = new AcxiomPortal.SharedObjects.PortalService.File();
            string tempFileName = Path.GetRandomFileName();
            file = manager.CreateFile(tenant, tempFileName, parentId, userId, fileSize);

            try
            {
                SaveFile(context.Request.InputStream, file.UUID);
            }
            catch (Exception ex)
            {
                manager.DeleteFile(file.NodeID);
                throw new Exception(ex.Message, ex.InnerException);
            }

            manager.FinishUploading(tenant, file.NodeID, filename, userId);
            manager.LogActivity("Add", "Document Repository", string.Format("Add {0}-{1} to {2};", file.NodeID, file.Name, parentId), userId, "", tenant);

            if (complete)
            {
                if (FileUploadCompleted != null)
                {
                    FileUploadCompletedEventArgs args = new FileUploadCompletedEventArgs(filename, "");
                    FileUploadCompleted(this, args);
                }
            }
        }
    }
    catch (Exception ex)
    { throw new Exception("DC.SilverlightFileUpload.ProcessRequest(): " + ex.Message, ex.InnerException); }
}

SaveFile方法看起来像这样:

private void SaveFile(Stream stream, string guid)
{
    try
    {
        byte[] buffer;

        int blockSize = 1024 * 2048;
        int bytesToRead = (int)stream.Length;
        int bytesRead = 0;

        using(DocumentServiceClient client = new DocumentServiceClient())
        {
            //buffer = new byte[stream.Length];
            //int n = stream.Read(buffer, 0, buffer.Length);

            //client.UploadFile(guid, buffer);

            while (bytesToRead > 0)
            {
                int length = blockSize < bytesToRead ? blockSize : bytesToRead;
                buffer = new byte[length];
                int n = stream.Read(buffer, 0, length);

                if (n == 0)
                    break;

                client.UploadFileByChunk(guid, buffer);

                bytesToRead -= n;
                bytesRead += n;
            }
        }
    }
    catch (Exception ex)
    {
        throw new Exception("DC.SilverlightFileUpload.SaveFile(): " + ex.Message, ex.InnerException);
    }
}

0 个答案:

没有答案