Apache Commons Fileupload - 上传后获取损坏的文件

时间:2013-03-11 07:11:50

标签: java jsp apache-commons-fileupload apache-commons-io

我使用以下代码成功上传了一个文本文件(比如Another.java),但在尝试打开上传的文件时却出错了。提前谢谢。

fileUpload.jsp

<form action="test.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<br/>
<input type="submit" value="Upload">
</form>
</body>

test.jsp的

<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="java.io.*"%>
<%@page import="java.util.*"%>
<%-- <%@page import="org.apache.commons.io.*" %> --%>
<%@page import="org.apache.commons.io.*"%>

<%@page import="org.apache.commons.fileupload.FileUploadException"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
    try {
        String username = "";
        List<FileItem> items = new ServletFileUpload(
                new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();

                if (fieldname.equals("vsrd")) {
                    username = fieldvalue;
                }

                // ... (do your job here)
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();

                String filename = FilenameUtils.getName(item.getName());

                InputStream filecontent = item.getInputStream();

                byte[] b = new byte[filecontent.available()];
                FileOutputStream fos = new FileOutputStream(
                        "/home/visruth/Desktop/Out" + filename);
                fos.write(b);
                fos.close();
                // ... (do your job here)
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }
%>
尝试打开OutAnother.java时出现

错误:

enter image description here

2 个答案:

答案 0 :(得分:1)

在您的代码中,您刚刚创建了一个空字节数组。您还没有从InputStream中读取内容。 Inputstream#available()只获得可用长度。它不会读取InputStream中的内容。

典型的方法是从InputStream读取并写入OutputStream:

FileInputStream is = new FileInputStream(
        new File("D:\\temp\\in.java"));
FileOutputStream os = new FileOutputStream(
        new File("D:\\temp\\out.java"));
byte[] buff = new byte[1000];
int length = -1;
while ((length = is.read(buff)) != -1) {
    os.write(buff, 0, length);
}
is.close();
os.close();

您也可以使用commons-io中的IOUtils#copy来完成这项工作。

答案 1 :(得分:0)

我通过添加以下代码修复了它:

byte[] b = new byte[filecontent.available()];
filecontent.read(b);