2

RahulSinglaによって開発されたExtJsFileManagerを使用してい ますhttp://www.rahulsingla.com/blog/2011/05/extjsfilemanager-extjs-based-file-and-image-manager-plugin-for-tinymce

これがPhpとC#の例であり、そのためのファイルハンドラーがあります。私は自分のプロジェクトでJavaSpringSourceを使用していますが、これらのテクノロジーは初めてです。C#をJavaに変換しようとしましたが、C#がクライアントに何を返すのか正確にはわかりません。

これがworkindC#コードです

<%@ 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 に答える