0

我在文件夹中创建了一个项目,ofbiz/hot-deployproductionmgntSystem. 在文件夹中ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem,我创建了一个.ftl文件,即app_details_1.ftl.以下是该文件的代码

<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>
        <script TYPE="TEXT/JAVASCRIPT" language=""JAVASCRIPT">
            function uploadFile()
            {
                //alert("Before calling upload.jsp");
                window.location='<@ofbizUrl>testing_service1</@ofbizUrl>'

            }

        </script>
    </head>
        <!-- <form action="<@ofbizUrl>testing_service1</@ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> -->
        <form action="<@ofbizUrl>logout1</@ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> 
        <center style="height: 299px; ">
            <table border="0" style="height: 177px; width: 788px">
                <tr style="height: 115px; ">
                    <td style="width: 103px; ">
                    <td style="width: 413px; "><h1>APPLICATION DETAILS</h1>
                    <td style="width: 55px; ">
                </tr>
                <tr>
                    <td style="width: 125px; ">Application name : </td>
                    <td>
                        <input name="app_name_txt" id="txt_1" value=" " />
                    </td>
                </tr>
                <tr>
                    <td style="width: 125px; ">Excell sheet &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: </td>
                    <td>
                        <input type="file" name="filename"/>
                    </td>
                </tr>
                <tr>
                    <td>
                       <!-- <input type="button" name="logout1_cmd" value="Logout" onclick="logout1()"/> -->
                       <input type="submit" name="logout_cmd" value="logout"/>
                    </td>
                    <td>
                        <!-- <input type="submit" name="upload_cmd" value="Submit" /> -->
                        <input type="button" name="upload1_cmd" value="Upload" onclick="uploadFile()"/>
                    </td>                   
                </tr>
            </table>
        </center>
    </form>
</html>

以下编码存在于文件“ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem\WEB-INF\controller.xml”中

......
.......
........
<request-map uri="testing_service1">
            <security https="true" auth="true"/>            
            <event type="java" path="org.ofbiz.productionmgntSystem.web_app_req.WebServices1" invoke="testingService"/>
            <response name="ok" type="view" value="ok_view"/>
            <response name="exception" type="view" value="exception_view"/>         
        </request-map>
..........
............
..........
<view-map name="ok_view" type="ftl" page="ok_view.ftl"/>        
<view-map name="exception_view" type="ftl" page="exception_view.ftl"/> 
................
.............
.............

以下是文件中的代码ofbiz\hot-deploy\productionmgntSystem\src\org\ofbiz\productionmgntSystem\web_app_req\WebServices1.java

package org.ofbiz.productionmgntSystem.web_app_req;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class WebServices1
{
    public static String testingService(HttpServletRequest request, HttpServletResponse response)
    {
        //int i=0;
        String result="ok";
        System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- Start");
        String contentType=request.getContentType();
        System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- contentType : "+contentType);
        String str=new String();
        // response.setContentType("text/html");
        //PrintWriter writer;
        if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
        {
            System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) after if (contentType != null)");
            try
            {
                // writer=response.getWriter();
                System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try Start");
                DataInputStream in = new DataInputStream(request.getInputStream());
                int formDataLength = request.getContentLength();
                byte dataBytes[] = new byte[formDataLength];
                int byteRead = 0;
                int totalBytesRead = 0;

                //this loop converting the uploaded file into byte code
                while (totalBytesRead < formDataLength)
                {
                    byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
                    totalBytesRead += byteRead;
                }

                String file = new String(dataBytes);
                //for saving the file name
                String saveFile = file.substring(file.indexOf("filename=\"") + 10);
                saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
                saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));
                int lastIndex = contentType.lastIndexOf("=");
                String boundary = contentType.substring(lastIndex + 1,contentType.length());
                int pos;

                //extracting the index of file
                pos = file.indexOf("filename=\"");
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                int boundaryLocation = file.indexOf(boundary, pos) - 4;
                int startPos = ((file.substring(0, pos)).getBytes()).length;
                int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

                //creating a new file with the same name and writing the content in new file
                FileOutputStream fileOut = new FileOutputStream("/"+saveFile);
                fileOut.write(dataBytes, startPos, (endPos - startPos));
                fileOut.flush();
                fileOut.close();
                System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try End");
            }
            catch(IOException ioe)
            {
                System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch IOException");
                //ioe.printStackTrace();
                return("exception");
            }
            catch(Exception ex)
            {
                System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch Exception");
                return("exception");
            }
        }
        else
        {
            System.out.println("\n\n\t********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) else part");
            result="exception";
        }
        System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- End");
        return(result);
    }
}

我想将文件上传到服务器。该文件是从文件中的用户<input type="file"..>标签获取的,并通过使用类中app_details_1.ftl的方法将其更新到服务器中。但是文件没有上传。testingService(HttpServletRequest request, HttpServletResponse response)WebServices1

4

2 回答 2

2

我得到了我的问题的解决方案。我成功地将文件上传到服务器。这个解决方案是我在与 ofbiz 的激烈斗争之后得到的。我对我的旧编码做了一些改动。下面给出。

以下是“app_details_1.ftl”中的编码

<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

        <!--<meta http-equiv="Content-Type" content="multipart/form-data; charset=ISO-8859-1">-->

        <title>Insert title here</title>
        <script TYPE="TEXT/JAVASCRIPT" language=""JAVASCRIPT">
            function uploadFile()
            {
                //alert("Before calling upload.jsp");
                window.location='<@ofbizUrl>testing_service1</@ofbizUrl>'

            }

            function logout1()
            {
                //alert("Logout1");
                alert("<@ofbizUrl>logout1</@ofbizUrl>");
                window.location='<@ofbizUrl>logout1</@ofbizUrl>'
            }
        </script>
        </head>
        <!-- <form action="<@ofbizUrl>testing_service1</@ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> -->
        <body bgcolor="cyan">
            <form enctype="multipart/form-data" action="<@ofbizUrl>uploadAttachFile</@ofbizUrl>" METHOD=POST>
                <center style="height: 299px;">
                    <table border="0" style="height: 177px; width: 788px">
                        <tr style="height: 115px; ">
                            <td style="width: 103px; ">
                            <td style="width: 440px; "><h1>APPLICATION DETAILS</h1>
                            <td style="width: 55px; ">
                        </tr>
                        <tr>
                            <td style="width: 125px; ">Application name : </br></td>
                            <td>
                                <input name="app_name_txt" id="txt_1" value=" " />
                            </td>
                            <td></br></br></td>
                        </tr>
                        <tr>
                            <td style="width: 125px; ">Excell sheet &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: </td>
                            <td>
                                <input type="file" name="filename"/>
                            </td>
                            <td></br></br></td>
                        </tr>
                        <tr>
                            <td>
                            <td></br>
                            <td>
                        </tr>
                        <tr>
                            <td>
                               <input type="button" name="logout1_cmd" value="LOGOUT" onclick="logout1()"/>
                              <!-- <input type="submit" name="logout_cmd" value="logout"/>-->
                            </td>
                            <td>
                                <input type="submit" name="upload_cmd" value="UPLOAD" />
                                <!-- <input type="button" name="upload1_cmd" value="Upload" onclick="uploadFile()"/> -->
                            </td>
                        </tr>
                    </table>
                </center>
            </form>
        </body>
</html>

这里我主要更改了表单操作属性。

以下是“controller.xml”中的代码片段

...............
.............
<request-map uri="uploadAttachFile">
            <security https="true" auth="true"/>
           <!--  <event type="simple" invoke="createCommunicationContent" path="component://productionmgntSystem/script/org/ofbiz/productionmgntSystem/CommunicationEventEvents.xml"/>  -->

           <event type="java" path="org.ofbiz.productionmgntSystem.web_app_req.Uploading" invoke="uploadFile"/>

            <response name="AttachementSuccess" type="view" value="AttachementSuccess"/>
            <response name="AttachementException" type="view" value="AttachementException"/>
        </request-map>    
................
.....................
<view-map name="AttachmentError" type="ftl" page="file_attach_error.ftl"/>
<view-map name="AttachementException" type="ftl" page="file_attach_error.ftl"/>
<view-map name="AttachementSuccess" type="ftl" page="AttachementSuccess.ftl"/>
...........
............

这里我应该将请求“uploadAttachFile”映射到事件“uploadFile”。即这个事件调用类“org.ofbiz.productionmgntSystem.web_app_req.Uploading”中的方法“uploadFile”。这个类是由我定义的。实际上是文件uplaod 在 ofbiz 中有我只是复制编码并为我的应用程序更改了一些更改。

在“uploadFile”方法中,我编写了将文件上传到服务器的编码。我将类“org.ofbiz.productionmgntSystem.web_app_req.Uploading”存储在以下文件夹“ofbiz\hot-deploy\productionmgntSystem\src\org\ofbiz\productionmgntSystem\web_app_req”中。这里的“productionmgntSystem”是我的应用程序名称。

以下是“org.ofbiz.productionmgntSystem.web_app_req.Uploading”类中的编码

//UPLOADING A CONTENT TO THE SERVER

package org.ofbiz.productionmgntSystem.web_app_req;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.ofbiz.service.ServiceUtil;
import java.util.List;

public class Uploading
{
    public static String uploadFile(HttpServletRequest request,HttpServletResponse response)
    {
        //ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory(10240, new File(new File("runtime"), "tmp")));           //Creation of servletfileupload
        System.out.println("\n\n\t****************************************\n\tuploadFile(HttpServletRequest request,HttpServletResponse response) - start\n\t");
        ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory());           //Creation of servletfileupload
        java.util.List lst = null;
        String result="AttachementException";
        String file_name="";
        try 
        {
            lst = fu.parseRequest(request);
        }
        catch (FileUploadException fup_ex) 
        {
            System.out.println("\n\n\t****************************************\n\tException of FileUploadException \n\t");
            fup_ex.printStackTrace();
            result="AttachementException";
            return(result);
        }

        if(lst.size()==0)        //There is no item in lst
        {
            System.out.println("\n\n\t****************************************\n\tLst count is 0 \n\t");
            result="AttachementException";
            return(result);
        }


        FileItem file_item = null;
        FileItem selected_file_item=null;

        //Checking for form fields - Start
            for (int i=0; i < lst.size(); i++) 
            {
                file_item=(FileItem)lst.get(i);
                String fieldName = file_item.getFieldName();

                //Check for the attributes for user selected file - Start
                    if(fieldName.equals("filename"))
                    {
                        selected_file_item=file_item;
                        //String file_name=file_item.getString();                       
                        //file_name=request.getParameter("filename");
                        file_name=file_item.getName();             //Getting the file name
                        System.out.println("\n\n\t****************************************\n\tThe selected file item's file name is : "+file_name+"\n\t");
                        break;
                    }
                //Check for the attributes for user selected file - End
            }
        //Checking for form fields - End

        //Uploading the file content - Start
            if(selected_file_item==null)                    //If selected file item is null
            {
                System.out.println("\n\n\t****************************************\n\tThe selected file item is null\n\t");
                result="AttachementException";
                return(result);
            }

            byte[] file_bytes=selected_file_item.get();
            byte[] extract_bytes=new byte[file_bytes.length];

            for(int l=0;l<file_bytes.length;l++)
                extract_bytes[l]=file_bytes[l];
            //ByteBuffer byteWrap=ByteBuffer.wrap(file_bytes);
            //byte[] extract_bytes;
            //byteWrap.get(extract_bytes);


            //System.out.println("\n\n\t****************************************\n\tExtract succeeded :content are : \n\t");


            if(extract_bytes==null)
            {
                System.out.println("\n\n\t****************************************\n\tExtract bytes is null\n\t");
                result="AttachementException";
                return(result);
            }

            /*
            for(int k=0;k<extract_bytes.length;k++)
                System.out.print((char)extract_bytes[k]);
            */

            //String target_file_name="/hot-deploy/productionmgntSystem"
            //Creation & writing to the file in server - Start              
                try
                {
                    FileOutputStream fout=new FileOutputStream(file_name);
                    System.out.println("\n\n\t****************************************\n\tAfter creating outputstream");
                    fout.flush();
                    fout.write(extract_bytes);
                    fout.flush();
                    fout.close();
                }
                catch(IOException ioe_ex)
                {
                    System.out.println("\n\n\t****************************************\n\tIOException occured on file writing");
                    ioe_ex.printStackTrace();
                    result="AttachementException";
                    return(result);
                }
            //Creation & writing to the file in server - End

            System.out.println("\n\n\t****************************************\n\tuploadFile(HttpServletRequest request,HttpServletResponse response) - end\n\t");
            return("AttachementSuccess");
        //Uploading the file content - End
    }
}

现在在我的应用程序中,我能够将文件上传到服务器。

于 2010-12-29T13:04:05.987 回答
0

如果你不想用 ftl 写,想用简单的形式写,这里是我的代码。但首先让我感谢 SIVAKUMAR.J 让我走上正轨。

这是表单的代码:

<form name="ImportBulkAttendance" target="uploadFileJava" type="upload" default-map-name="content" focus-field-name="contentTypeId" header-row-style="header-row" default-table-style="basic-table">

    <field name="filename" title="filename">
        <file name="filename"/>
    </field>
    <field name="createButton">
        <submit button-type="button" />
    </field>
</form>

然后在controller.xml

   <request-map uri="uploadFileJava">
    <security https="true" auth="true"/>
    <event type="java" path="com.ofbiz.attendance.Uploading" invoke="uploadFile"/>
   </request-map>
<view-map name="AttachmentError" type="screen" page="component://yourComponentName/widget/yourComponentNameScreens.xml#main"/>

在项目的此路径中创建 ant 丢失文件夹:yourComponentFolder/src/ofbiz/attendance/ 然后创建 Uploading.java

package com.ofbiz.attendance;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.ofbiz.service.ServiceUtil;
import java.util.List;

public class Uploading
{
    public static String uploadFile(HttpServletRequest request,HttpServletResponse response)
    {
        //ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory(10240, new File(new File("runtime"), "tmp")));           //Creation of servletfileupload
        System.out.println("\n\n\t****************************************\n\tuploadFile(HttpServletRequest request,HttpServletResponse response) - start\n\t");
        ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory());           //Creation of servletfileupload
        java.util.List lst = null;
        String result="AttachementException";
        String file_name="";
        try 
        {
            lst = fu.parseRequest(request);
        }
        catch (FileUploadException fup_ex) 
        {
            System.out.println("\n\n\t****************************************\n\tException of FileUploadException \n\t");
            fup_ex.printStackTrace();
            result="AttachementException";
            return(result);
        }
    if(lst.size()==0)        //There is no item in lst
    {
        System.out.println("\n\n\t****************************************\n\tLst count is 0 \n\t");
        result="AttachementException";
        return(result);
    }


    FileItem file_item = null;
    FileItem selected_file_item=null;

    //Checking for form fields - Start
        for (int i=0; i < lst.size(); i++) 
        {
            file_item=(FileItem)lst.get(i);
            String fieldName = file_item.getFieldName();

            //Check for the attributes for user selected file - Start
                if(fieldName.equals("filename"))
                {
                    selected_file_item=file_item;
                    //String file_name=file_item.getString();                       
                    //file_name=request.getParameter("filename");
                    file_name=file_item.getName();             //Getting the file name
                    System.out.println("\n\n\t****************************************\n\tThe selected file item's file name is : "+file_name+"\n\t");
                    break;
                }
            //Check for the attributes for user selected file - End
        }
    //Checking for form fields - End

    //Uploading the file content - Start
        if(selected_file_item==null)                    //If selected file item is null
        {
            System.out.println("\n\n\t****************************************\n\tThe selected file item is null\n\t");
            result="AttachementException";
            return(result);
        }

        byte[] file_bytes=selected_file_item.get();
        byte[] extract_bytes=new byte[file_bytes.length];

        for(int l=0;l<file_bytes.length;l++)
            extract_bytes[l]=file_bytes[l];
        //ByteBuffer byteWrap=ByteBuffer.wrap(file_bytes);
        //byte[] extract_bytes;
        //byteWrap.get(extract_bytes);


        //System.out.println("\n\n\t****************************************\n\tExtract succeeded :content are : \n\t");


        if(extract_bytes==null)
        {
            System.out.println("\n\n\t****************************************\n\tExtract bytes is null\n\t");
            result="AttachementException";
            return(result);
        }

        /*
        for(int k=0;k<extract_bytes.length;k++)
            System.out.print((char)extract_bytes[k]);
        */

        //String target_file_name="/hot-deploy/productionmgntSystem"
        //Creation & writing to the file in server - Start              
            try
            {
                FileOutputStream fout=new FileOutputStream(file_name);
                System.out.println("\n\n\t****************************************\n\tAfter creating outputstream");
                fout.flush();
                fout.write(extract_bytes);
                fout.flush();
                fout.close();
            }
            catch(IOException ioe_ex)
            {
                System.out.println("\n\n\t****************************************\n\tIOException occured on file writing");
                ioe_ex.printStackTrace();
                result="AttachementException";
                return(result);
            }
        //Creation & writing to the file in server - End

        System.out.println("\n\n\t****************************************\n\tuploadFile(HttpServletRequest request,HttpServletResponse response) - end\n\t");
        return("AttachementSuccess");
    //Uploading the file content - End
}


}

就是复制具有相同名称的文件,它们应该直接工作:) 我希望这可以节省某人的时间。注意:您不需要创建 XML 服务。

于 2015-11-09T14:05:42.043 回答