首页 > 代码库 > jfinal初接触,一个简单的文件上传例子

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

写了个上传的小例子。

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

然后下载jfinal-1.8-lib.zip

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

 

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

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

CommonController.java :

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=http://www.mamicode.com/"./\">back</a>");    }        }

index.jsp:

<%@ 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 :

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();            }        }    }}

没有太多需要说明的,参考着官方的文档就可以了。