Java - 文件上传问题

时间:2011-03-09 11:38:30

标签: java html forms servlets file-upload

的Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;

public class Apply extends HttpServlet
{
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
                            throws ServletException, IOException
    {
        InputStreamReader input = new InputStreamReader(request.getInputStream());
        BufferedReader buffer = new BufferedReader(input);
        String line="";
        line=buffer.readLine();

        System.out.println("Multipart data " + line );

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(isMultipart)
        {
            // upload file
        }
        else
        {
            // failed, no input
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
                            throws ServletException, IOException
    {
        doPost(request, response);
    }
}

JSP。

        <form enctype="multipart/form-data" method="post" action="apply">
            <fieldset>
                <br/>
                <legend>Upload</legend>
                <br/>
                <label>Select file to upload</label>
                <input type="file" name="file" /><br />
                <br/>
                <a href="apply" class="jUiButton">Submit</a>
            </fieldset>
        </form>     
        <script>$(".jUiButton").button()</script>

布尔值和输入总是验证为false / null,我无法理解为什么。遵循本指南:http://sacharya.com/file-upload/

在web-inf / lib中的

- 我们有commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar。

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

您实际上并未提交表单。您正在使用GET请求导航到该页面。

使用提交按钮替换“提交”锚点:

<button type="submit" class="jUiButton">Submit</button>

您可以保留<a>,但之后您必须使用JavaScript手动提交表单。

答案 1 :(得分:1)

您不应事先阅读HttpServletRequest#getInputStream()。它只能读一次。如果您事先已经阅读过,Commons FileUpload将无法读取它。在ServletFileUpload#isMultipartContent()行之前删除servlet中的所有行。

答案 2 :(得分:-1)

您所关注的指南已过期(2008年)。如果这是一个新项目,您可能希望从基于注释的方法开始。 This guide可能会更好(2010)。然后,文件上传控制器将如下所示:

@Controller
public class FileUploadContoller {   
    @RequestMapping(value = "/fileupload", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public String ingest(@RequestParam("file") final MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            System.out.println("empty");
        } else {
            System.out.println("not empty");
        }

        // do something with file.getBytes()

        return("ok");
    }
}

这只是控制器,您需要添加适当的Spring配置。如果你想沿着这条路走下去,我可以继续提供帮助。