jfinal 文件上传以来的jar包 cos-2017.5.jar
可以在jfinal 官网下载jfinal jar包下载
首先在config文件中的 configConstant方法中配置上传路径
me.setBaseUploadPath("upload/");
表单代码
这里注意要 form 里要加 enctype="multipart/form-data"并且提交方式 指定为post,否则会报错
<form method="post" action="/blog/upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
后台代码
public void upload(){
HttpServletRequest request = getRequest();
String basePath = request.getContextPath();
//存储路径
String path = getSession().getServletContext().getRealPath(Preference._PATH);
UploadFile file = getFile("file");
System.out.println(path);
String fileName = "";
if(file.getFile().length() > 200*1024*1024) {
System.err.println("文件长度超过限制,必须小于200M");
}else{
//上传文件
String type = file.getFileName().substring(file.getFileName().lastIndexOf(".")); // 获取文件的后缀
fileName = System.currentTimeMillis() + type; // 对文件重命名取得的文件名+后缀
String dest = path + "/" + fileName;
file.getFile().renameTo(new File(dest));
String realFile = basePath + "/" + Preference._PATH + fileName;
String fname="/"+fileName;
setAttr("fname", fname);
setAttr("url", realFile);
}
renderJson();
}
public final class Preference {
public static String _PATH = "upload/test/";
}
程序员的网址收藏夹