jfinal初接触,一个简单的文件上传例子

写了个上传的小例子。html

从jfinal官网下载jfinal-1.8_demo_for_jsp.zipjava

而后下载jfinal-1.8-lib.zipdom

按要求删掉该删除的,引入一些包,以后的项目结构:jsp

 

DemoConfig.java中配置路由,只留下了根路径:post

    /**
     * 配置路由
     */
    public void configRoute(Routes me) {
        me.add("/", CommonController.class);
        //me.add("/blog", BlogController.class);
    }

CommonController.java :ui

package com.demo.common;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;

/**
 * CommonController
 */
public class CommonController extends Controller {
    
    public void index() {
        render("/index.jsp");
    }
    
    public void uploadFile(){
    
        
        UploadFile uploadFile=this.getFile();

        
        String fileName=uploadFile.getOriginalFileName();
        
        
        File file=uploadFile.getFile();    
        FileService fs=new FileService();    
        File t=new File("S:\\file\\"+UUID.randomUUID().toString());
        try {
            t.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        fs.fileChannelCopy(file, t);
        file.delete();
        this.renderHtml("success,<a href=\"./\">back</a>");
    }
    
    
}

index.jsp:this

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="zh-CN" xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

</head>
<body>



<form action="uploadFile" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit"/>
</form>
</body>
</html>

FileService.java :spa

package com.demo.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FileService {

    public void fileChannelCopy(File s, File t) {

        FileInputStream fi = null;

        FileOutputStream fo = null;

        FileChannel in = null;

        FileChannel out = null;

        try {

            fi = new FileInputStream(s);

            fo = new FileOutputStream(t);

            in = fi.getChannel();// 获得对应的文件通道

            out = fo.getChannel();// 获得对应的文件通道

            in.transferTo(0, in.size(), out);// 链接两个通道,而且从in通道读取,而后写入out通道

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                fi.close();

                in.close();

                fo.close();

                out.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }
}

没有太多须要说明的,参考着官方的文档就能够了。code

相关文章
相关标签/搜索