美文网首页
文件上传

文件上传

作者: exmexm | 来源:发表于2017-07-01 11:10 被阅读0次

一、上传单个文件
1、在WEB-INF/lib下加入commons-fieupload-1.2.xx.jar、commons-io-1.3.x.jar。
2、一定要记得将enctpye设置为"multipart/form-data",如下:

<form action="logon" enctype="multipart/form-data" method="post">
            姓名:<input type="text" name="person.username"><br>
            生日:<input type="text" name="person.birthday"><br>       
            密码:<input type="password" name="person.password"><br>
            <input type="file" name="image">
            <input type="submit" name="submit" value="提交"><br>
        </form>

3、在Action类中添加以下属性,对应于表单内上传文件的name属性,在这里即image。
具体如下:

    public String login() throws IOException {
        String filePath = ServletActionContext.getServletContext().getRealPath("/image");
        System.out.println(filePath);
        if (image != null) {
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            File toSave = new File(file, imageFileName);
            FileUtils.copyFile(image, toSave);
        }
        return "success";
    }

二、多文件上传
1、在WEB-INF/lib下加入commons-fieupload-1.2.xx.jar、commons-io-1.3.x.jar。
2、一定要记得将enctpye设置为"multipart/form-data",且上传文件的字段名要相同如下:

<form action="logon" enctype="multipart/form-data" method="post">
            <input type="file" name="images">
            <input type="file" name="images">
            <input type="submit" name="submit" value="提交"><br>
        </form>

3、在action中添加一下属性,且属性的名称要和表单的字段名相同,而且类型是用数组的类型或者list类型。如下:

private File[] images;
private String[] imagesFileName;
public File[] getImages() {
        return images;
    }

    public void setImages(File[] images) {
        this.images = images;
    }

    public String[] getImagesFileName() {
        return imagesFileName;
    }

    public void setImagesFileName(String[] imagesName) {
        this.imagesFileName = imagesName;
    }
public String login() throws IOException {
        String filePath = ServletActionContext.getServletContext().getRealPath("/image");
        System.out.println(filePath);
        if (images != null) {
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            System.out.println(images.length);
            for (int i = 0; i < images.length; i++) {
                File toSave = new File(file, imagesFileName[i]);
                FileUtils.copyFile(images[i], toSave);
            }
        }
        return "success";
    }

相关文章

网友评论

      本文标题:文件上传

      本文链接:https://www.haomeiwen.com/subject/yjuwcxtx.html