2

我正在使用由 Rahul Singla http://www.rahulsingla.com/blog/2011/05/extjsfilemanager-extjs-based-file-and-image-manager-plugin-for-tinymce开发的 ExtJsFileManager

这里是 Php 和 C# 示例,并且有它的文件处理程序。我在我的项目中使用 Java SpringSource,我对这些技术不熟悉。我试图将 C# 转换为 Java,但我不明白 C# 返回给客户端的确切内容。

这是工作 C# 代码

<%@ WebHandler Language="C#" Class="BrowserHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using MyCompany;

public class BrowserHandler : IHttpHandler
{

#region Private Members
private HttpContext context;
#endregion

#region IHttpHandler Methods
public void ProcessRequest (HttpContext context)
{
    this.context = context;
    string op=context.Request["op"];
    string path=this.context.Request["path"];
    context.Response.ContentType = "text/javascript";

    //These are extra parameters you can pass to the server in each request by specifying extjsfilemanager_extraparams option in init.
    string param1=context.Request["param1"];
    string param2=context.Request["param2"];

    switch (op)
    {
        case "getFolders":
            this.getFolders(path);
            break;

        case "getFiles":
            this.getFiles(path);
            break;

        case "createFolder":
            this.createFolder(path);
            break;

        case "uploadFiles":
            this.uploadFiles(path);
            break;
    }
}

public bool IsReusable
{
    get
    {
        return false;
    }
}
#endregion

#region Private Methods
private void getFolders (string path)
{
    path = this.validatePath(path);

    List<object> l=new List<object>();
    foreach (string dir in Directory.GetDirectories(path))
    {
        l.Add(new
        {
            text = Path.GetFileName(dir),
            path = dir,
            leaf = false,
            singleClickExpand = true
        });
    }

    this.context.Response.Write(Globals.serializer.Serialize(l));
}

private void getFiles (string path)
{
    path = this.validatePath(path);

    List<object> l=new List<object>();
    foreach (string file in Directory.GetFiles(path))
    {
        l.Add(new
        {
            text = Path.GetFileName(file),
            virtualPath = Globals.resolveUrl(Globals.resolveVirtual(file))
        });
    }

    this.context.Response.Write(Globals.serializer.Serialize(l));
}

private void createFolder (string path)
{
    path = this.validatePath(path);

    string name=this.context.Request["name"];
    Directory.CreateDirectory(Path.Combine(path, name));

    this.context.Response.Write(Globals.serializer.Serialize(new object()));
}

private void uploadFiles (string path)
{
    context.Response.ContentType = "text/html";
    path = this.validatePath(path);

    string successFiles="";
    string errorFiles="";

    for (int i=0; i < this.context.Request.Files.Count; i++)
    {
        HttpPostedFile file=this.context.Request.Files[i];

        if (file.ContentLength > 0)
        {
            string fileName=file.FileName;
            string extension=Path.GetExtension(fileName);
            //Remove .
            if (extension.Length > 0) extension = extension.Substring(1);

            if (Config.allowedUploadExtensions.Contains(extension, StringComparer.InvariantCultureIgnoreCase))
            {
                file.SaveAs(Path.Combine(path, fileName));
            }
            else
            {
                errorFiles += string.Format("Extension for {0} is not allowed.<br />", fileName);
            }
        }
    }

    string s=Globals.serializer.Serialize(new
    {
        success = true,
        successFiles,
        errorFiles
    });
    byte[] b=this.context.Response.ContentEncoding.GetBytes(s);
    this.context.Response.AddHeader("Content-Length", b.Length.ToString());

    this.context.Response.BinaryWrite(b);

    try
    {
        this.context.Response.Flush();
        this.context.Response.End();
        this.context.Response.Close();
    }
    catch (Exception) { }
}

private string validatePath (string path)
{
    if (string.IsNullOrEmpty(path))
    {
        path = Config.baseUploadDirPhysical;
    }

    if (!path.StartsWith(Config.baseUploadDirPhysical, StringComparison.InvariantCultureIgnoreCase) || (path.IndexOf("..") != -1))
    {
        throw new SecurityException("Invalid path.");
    }

    return (path);
}
#endregion}

这是我的代码

@RequestMapping(value = "/filehandler", method = RequestMethod.POST)
public @ResponseBody byte[] filehandler(HttpServletRequest request, HttpServletResponse response) {
    String op = request.getParameter("op");
    String path = uploadDataFolder; // || request.getParameter("path");
    String jsondata = "{root:";
    String datastr = "";

    File folder = new File(path);

    if (op.equals( "getFolders")){
        // FOLDERS
        for (File fileEntry : folder.listFiles() ) {
            //File fileEntry;
            if (fileEntry.isDirectory()) {
                datastr += "{\"text\":\"" + fileEntry.getName() +
                            "\",\"path\":\"" + fileEntry.getPath() +
                            "\",\"leaf\":\"false\"" +
                            ",\"singleClickExpand\":\"true\"}";
            }
        }
    }
    else if (op == "getFiles"){
        // FILES
        for (File fileEntry : folder.listFiles()) {
            //File fileEntry;
            if (fileEntry.isFile()) {
                datastr += "{\"text\":\"" + fileEntry.getName() +
                            "\",\"virtualPath\":\"" + fileEntry.getPath() + "\"";
            } else {
                System.out.println(fileEntry.getName());
            }
        }
    }
    else if (op == "createFolder"){
        // create folder function is not supported in our project

    }
    else if (op == "uploadFiles"){
        // upload images
        request.getAttribute("Files");
    }
    datastr = datastr.equals("") ? "null" :  "[" + datastr + "]";
    jsondata += datastr + "}";

    return getBytes(jsondata);
}

对于 getFolders 操作,它返回 JSON 数据,例如

{root:[{"text":"blog","path":"C:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NetaCommerceFrameworkAdmin\META-INF\static\images\blog","leaf":"false","singleClickExpand":"true"}{"text":"photos","path":"C:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\NetaCommerceFrameworkAdmin\META-INF\static\images\photos","leaf":"false","singleClickExpand":"true"}]}

我无法弄清楚 C# 代码返回什么,所以我无法用 Java 编写它。它不允许“getFolders”操作返回我的 JSON。

4

1 回答 1

2

AC# 'HTTPHandler' 可以返回它想要的东西,例如它可以返回一个图像(一种常见用途),或者它可以返回二进制文件数据,让客户端下载一个文件。

它们很灵活,可以配置为“返回”任何内容,因为它们经常直接写入 HTTPResponse 对象。

为了弄清楚您的处理程序返回的内容,您需要寻找任何触及 HTTPResponse 的内容。

例如context.Response.ContentType = "text/javascript";

这是在 Http 响应上设置内容类型标头。

那里的几个私有方法似乎会生成列表,并将那些序列化的列表返回给客户端,看起来就像 JSON 数据。

这里的例外是uploadFiles()似乎接受发布请求的方法(您可以知道它正在尝试访问请求对象以在此处检索上传的文件:

HttpPostedFile file=this.context.Request.Files[i];

经过一些检查后,这似乎将文件保存到服务器。

如果我是你,我会在 Java API 中寻找他们自己的序列化器选项,看看你是否可以挂钩,而不是编写自己的方法来将字符串粘在一起。

于 2012-12-31T09:19:02.560 回答