【问题标题】:FileUpload problem with Struts on server服务器上 Struts 的 FileUpload 问题
【发布时间】:2011-04-23 19:34:22
【问题描述】:

我正在尝试创建一个上传 servlet,用于处理来自表单的 enctype="multipart/form-data"。我要上传的文件是 zip。但是,我可以在 localhost 上上传和读取文件,但是当我上传到服务器时,当我想上传文件时出现“找不到文件”错误。这是由于我使用的 Struts 框架造成的吗?谢谢你的帮助。这是我的代码的一部分,我正在使用来自 http://commons.apache.org/fileupload/using.html 的 FileUpload

我已更改为使用 ZipInputStream,但是,如何在不使用本地磁盘地址(即:C://zipfile.zip)的情况下引用 ZipFile zip。 zip 为空,因为它没有被实例化。我需要解压并读取内存中的 zipentry,而不是写入服务器。

对于上传 servlet: > 私人 ZipFile 压缩包; 私人 CSVReader 阅读器; boolean isMultipart = ServletFileUpload.isMultipartContent(request); 如果(是多部分){ DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload upload = new ServletFileUpload(factory);
       List <FileItem> items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            //Iterating through the uploaded zip file and reading the content
            FileItem item = (FileItem) iter.next();

             ZipInputStream input = new ZipInputStream(item.getInputStream()); 
             ZipEntry entry = null;
             while (( entry= input.getNextEntry()) != null) {
               ZipEntry entry = (ZipEntry) e.nextElement();
               if(entry.getName().toString().equals("file.csv")){
                   //unzip(entry)
               }

               }
            }


  public static void unzip(ZipEntry entry){
        try{
            InputStream inputStream = **zip**.getInputStream(entry);
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            reader = new CSVReader(inputStreamReader);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

【问题讨论】:

    标签: servlets file-upload struts2 zip


    【解决方案1】:

    这里,

    zip = new ZipFile(new File(fileName));
    

    您假设服务器机器上的本地磁盘文件系统已经包含与客户端名称完全相同的文件。这是一个错误的假设。它在本地主机上工作显然是因为网络浏览器和网络服务器“巧合”在物理上运行在具有相同磁盘文件系统的同一台机器上。

    另外,您似乎使用 Internet Explorer 作为浏览器,它错误地在文件名中包含完整路径,例如 C:/full/path/to/file.ext。您不应该依赖此浏览器特定的错误。其他浏览器(如 Firefox)仅正确发送像 file.ext 这样的文件名,这反过来会导致 new File(fileName) 失败(这应该可以帮助您更快地发现错误)。

    要解决这个“问题”,你需要通过item.getInputStream()获取文件contentsInputStream

    ZipInputStream input = new ZipInputStream(item.getInputStream());
    // ...
    

    或者通过item.write(file)将其写入磁盘并在ZipFile中引用:

    File file = File.createTempFile("temp", ".zip");
    item.write(file);
    ZipFile zipFile = new ZipFile(file);
    // ...
    

    注意:不要忘记事先检查文件扩展名,否则可能会窒息。

    【讨论】:

    • 感谢您的回复,但我一直在引用 ZipFile zip。如果不引用实际文件,我无法让它工作,这在实际服务器上不起作用。我已经编辑了上面的代码。
    • 将其写入磁盘,然后将File 引用为ZipFile
    • 你的意思是 ZipFile zip = (ZipFile) item.write(file)?这个文件会引用到哪里?
    • 哦,是的,创建一个临时文件,我错过了。谢谢!
    猜你喜欢
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多