Javaweb文件上传的一个简单工具类
程序员文章站
2022-04-08 09:27:40
...
Javaweb文件上传的一个简单工具类
这是我根据别的例子还有自己的一些想法写的,很简单的,适合初学者看看。
package com.zxj.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadDemo {
public void test(HttpServletRequest request,HttpServletResponse response){
try {
//设定编码格式
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("utf-8");
//1、建立一个DiskFileItemFactory工厂
DiskFileItemFactory factory=new DiskFileItemFactory();
//2、建立一个文件上传解析器
ServletFileUpload upload=new ServletFileUpload(factory);
//3、解决上传文件的中文乱码
upload.setHeaderEncoding("UTF-8");
factory.setSizeThreshold(1024*500);//设置内存的临界值味500k
File temporary=new File("D:\\files");//设置当超过500K的时候存放到临时文件中
factory.setRepository(temporary);
upload.setSizeMax(1024*1024*5);//设置上传的文件总的大小不能超过5M
try {
//1、得到FileItem的集合items
List<FileItem> items=upload.parseRequest(request);
//2、遍历items
for (FileItem item : items) {
//1、若是一般的表单,打印
if(item.isFormField()){
String name=item.getFieldName();
String value=item.getString("UTF-8");
System.out.println("name="+name+",value="+value);
}else{//2、若是文件则保存到目标文件中
String fileName=item.getFieldName();
long fileByte=item.getSize();
//得到当前年份月份日期
Calendar now=Calendar.getInstance();
String year=String.valueOf(now.get(Calendar.YEAR));
String month=String.valueOf(now.get(Calendar.MONTH));
String day=String.valueOf(now.get(Calendar.DAY_OF_MONTH));
String mils=String.valueOf(System.currentTimeMillis());
String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
if(prefix.equals("jpg")){
System.out.println("请上传图片");
}
String fileName1= fileName.substring(0,fileName.lastIndexOf('.'));
fileName=fileName.replace(fileName1,mils);
//输入流
InputStream in=item.getInputStream();
byte[] buffer=new byte[1024];
int len=0;
String rest="d:\\files\\"+year+"\\"+month+"\\"+day+"\\";
//如果没有路径就创建
if(!new File(rest).exists()){
new File(rest).mkdir();
}
//存储地址
fileName=rest+fileName;
//输出流
OutputStream out=new FileOutputStream(fileName);
while((len=in.read(buffer))!=-1){
out.write(buffer,0,len);
}
out.close();
in.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
上一篇: 文件上传实现