欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

commons fileupload实现文件上传的实例代码

程序员文章站 2024-03-12 23:38:45
一、文件上传的原理分析     1、文件上传的必要前提       a、表单的method必须是post       b、表单的enctype属性必须是multipa...

一、文件上传的原理分析

    1、文件上传的必要前提

      a、表单的method必须是post

      b、表单的enctype属性必须是multipart/form-data类型的。

      enctype默认值:application/x-www-form-urlencoded

      作用:告知服务器,请求正文的mime类型

      application/x-www-form-urlencoded : username=abc&password=123

      servletrequest.getparameter(string name);该方法是专门读取该类型的方法

      multipart/form-data:

commons fileupload实现文件上传的实例代码

    2、借助commons-fileupload组件实现文件的上传

      a、拷贝jar包:commons-fileupload.jar commons-io.jar

      b、实现原理

commons fileupload实现文件上传的实例代码

    3、乱码问题

      a、普通字段的乱码

        fileitem.getstring(string charset);编码要和客户端一致

      b、上传的中文文件名乱码

        request.setcharacterencoding("utf-8");编码要和客户端一致

    4、具体实现

前台upload.jsp代码如下

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<title>文件上传</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="${pagecontext.request.contextpath}/servlet/uploadservlet3" method="post" enctype="multipart/form-data">
name:<input name="name"/><br/>
file1:<input type="file" name="f1"/><br/>
file2:<input type="file" name="f2"/><br/>
<input type="submit" value="上传">
</form>
</body>
</html>

后台servlet代码

package com.itheima.servlet;
import java.io.file;
import java.io.ioexception;
import java.io.printwriter;
import java.io.unsupportedencodingexception;
import java.util.list;
import java.util.uuid;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import org.apache.commons.fileupload.fileitem;
import org.apache.commons.fileupload.fileuploadbase;
import org.apache.commons.fileupload.fileuploadexception;
import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;
import org.apache.commons.io.filenameutils;
//详解
public class uploadservlet3 extends httpservlet {
public void doget(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
request.setcharacterencoding("utf-8");
response.setcontenttype("text/html;charset=utf-8");
printwriter out = response.getwriter();
system.out.print(request.getremoteaddr());
boolean ismultipart = servletfileupload.ismultipartcontent(request);
if(!ismultipart){
throw new runtimeexception("请检查您的表单的enctype属性,确定是multipart/form-data");
}
diskfileitemfactory dfif = new diskfileitemfactory();
servletfileupload parser = new servletfileupload(dfif);
// parser.setfilesizemax(3*1024*1024);//设置单个文件上传的大小
// parser.setsizemax(6*1024*1024);//多文件上传时总大小限制
list<fileitem> items = null;
try {
items = parser.parserequest(request);
}catch(fileuploadbase.filesizelimitexceededexception e) {
out.write("上传文件超出了3m");
return;
}catch(fileuploadbase.sizelimitexceededexception e){
out.write("总文件超出了6m");
return;
}catch (fileuploadexception e) {
e.printstacktrace();
throw new runtimeexception("解析上传内容失败,请重新试一下");
}
//处理请求内容
if(items!=null){
for(fileitem item:items){
if(item.isformfield()){
processformfield(item);
}else{
processuploadfield(item);
}
}
}
out.write("上传成功!");
}
private void processuploadfield(fileitem item) {
try {
string filename = item.getname();
//用户没有选择上传文件时
if(filename!=null&&!filename.equals("")){
filename = uuid.randomuuid().tostring()+"_"+filenameutils.getname(filename);
//扩展名
string extension = filenameutils.getextension(filename);
//mime类型
string contenttype = item.getcontenttype();
if(contenttype.startswith("image/")){
//分目录存储:日期解决
// date now = new date();
// dateformat df = new simpledateformat("yyyy-mm-dd");
// 
// string childdirectory = df.format(now);
//按照文件名的hashcode计算存储目录
string childdirectory = makechilddirectory(getservletcontext().getrealpath("/web-inf/files/"),filename);
string storedirectorypath = getservletcontext().getrealpath("/web-inf/files/"+childdirectory);
file storedirectory = new file(storedirectorypath);
if(!storedirectory.exists()){
storedirectory.mkdirs();
}
system.out.println(filename);
item.write(new file(storedirectorypath+file.separator+filename));//删除临时文件
}
}
} catch (exception e) {
throw new runtimeexception("上传失败,请重试");
}
}
//计算存放的子目录
private string makechilddirectory(string realpath, string filename) {
int hashcode = filename.hashcode();
int dir1 = hashcode&0xf;// 取1~4位
int dir2 = (hashcode&0xf0)>>4;//取5~8位
string directory = ""+dir1+file.separator+dir2;
file file = new file(realpath,directory);
if(!file.exists())
file.mkdirs();
return directory;
}
private void processformfield(fileitem item) {
string fieldname = item.getfieldname();//字段名
string fieldvalue;
try {
fieldvalue = item.getstring("utf-8");
} catch (unsupportedencodingexception e) {
throw new runtimeexception("不支持utf-8编码");
}
system.out.println(fieldname+"="+fieldvalue);
}
public void dopost(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
doget(request, response);
}
}

5、关于临时文件问题

    a、diskfileitemfactory

      public void setrepository(file repository):设置临时文件的存放目录
      public void setsizethreshold(int sizethreshold):设置缓存的大小

    b、     

      文件上传时,自己用io流处理,一定要在流关闭后删除临时文件。fileitem.delete()

      建议使用:fileitem.writer(file f).会自动删除临时文件。

    6、限制文件的大小

    a、 

      servletfileupload.setfilesizemax(3*1024*1024);//设置单个文件上传的大小

    b、

      servletfileupload.setsizemax(6*1024*1024);//多文件上传时总大小限制   

以上所述是小编给大家介绍的commons fileupload实现文件上传的实例代码,希望对大家有所帮助