文件上传的步骤
文件上传的步骤:
1.
2.首先要更改form的enctype="multipart/form-data"
表示向服务器传输的过程中以二进制的方式传输
默认传输类型: enctype="application/x-www-form-urlencoded"
3.相关jar包 下载地址 www.apache.org
commons-fileupload-1.2.1.jar 核心组件包
commons-io-2.0.1.jar --fileupload组件包,依赖了IO
commons-lang3-3.1.jar
commons-logging-1.1.3.jar
json-lib-2.4-jdk15.jar JSON工具类
struts2-json-plugin-2.3.15.1.jar
4.普通上传页面
`<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<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"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> `5.ajax上传页面
`<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
</head>
`
6.后台处理类
`<%@page import="org.apache.struts2.json.JSONUtil"%>
<%@page import="com.rui.util.StrUtils"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
/文件上传的方式/
//1.获取文件上传的工厂类
FileItemFactory factory = new DiskFileItemFactory();
//2.解析上传文件的工厂
ServletFileUpload fileUpload = new ServletFileUpload(factory);
//3.通过解析类解析request对象中的二进制文件
List
//4.读取二进制文件,写入服务器
//获取服务器的路径getRealPath()获取当前项目所在服务器的根目录
//D:\tool\dev\apache-tomcat-7.0.56-windows-x86\apache-tomcat-7.0.56\me-webapps\fileUpload\resource
String dirpath = request.getParameter("dirpath");//
if(StrUtils.isEmpty(dirpath)) dirpath = "default";
String fpath = "resource/"+dirpath;
String path = request.getRealPath(fpath);
File rootPath = new File(path);
//如果目录不存在就动态创建
if(!rootPath.exists()){
rootPath.mkdirs();
}
//如果有文件,就开始进行读和写
if(fileItems != null && fileItems.size()>0){
List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
for(FileItem fileItem : fileItems){
if(!fileItem.isFormField()){//判断是不是file表单
//获取文件名称
String filename = fileItem.getName();
//文件大小
long filesize = fileItem.getSize();
//获取文件后缀
String ext = StrUtils.getExt(filename, true);
//重构文件的名称===头像上传的原理就是文件的覆盖
String fname = UUID.randomUUID().toString()+ext;
File fileName = new File(rootPath,fname);
fileItem.write(fileName);
Map<String,Object> map = new HashMap<String,Object>();
map.put("name", filename);
map.put("size", filesize);
map.put("sizeString", StrUtils.countFileSize(filesize));
map.put("url", fpath+"/"+fname);
maps.add(map);
}
}
out.print(JSONUtil.serialize(maps));
}else {
out.print("");
//response.sendRedirect("fail.jsp");
}
//5.在服务器创建一个上传的目录
//6.开始写入
//7.返回数据
//response.sendRedirect("success.jsp");
%>`
7.工具类
`package com.rui.util;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
*
-
@ClassName: StrUtils
-
@Description: 工具类
-
@author poseidon
-
@date 2015年10月23日 下午8:13:45
-
@version V1.0.0
*/
public class StrUtils {/**
*- @Title: isEmpty
- @Description: 空判断
- @param content
- @return boolean
*/
public static boolean isEmpty(String content){
return (content==null || content.equals(""))?true:false;
}
/**
*- @Title: isNotEmpty
- @Description: 非空判断
- @param content
- @return boolean
*/
public static boolean isNotEmpty(String content){
return !isEmpty(content);
}
/**
*- @Title: formatDate
- @Description: 格式化日期类
- @param date
- @param pattern
- @return String
*/
public static String formatDate(Date date,String pattern){
if(date!=null){
String dateString = new SimpleDateFormat(pattern).format(date);
return dateString;
}else{
return "";
}
}
/**
*- @Title: getExt
- @Description: 获取文件的后缀
- @param name 文件名称
- @param flag true有点false没点
- @return String
*/
public static String getExt(String name,boolean flag){
if(isNotEmpty(name)){
String ext = null;
if(flag){
ext = name.substring(name.lastIndexOf("."), name.length());
}else{
ext = name.substring(name.lastIndexOf(".")+1, name.length());
}
return ext;
}else{
return "";
}
}
/**
*- @Title: generateFileName
- @Description: 为上传文件自动分配文件名称,避免重复
- @param fileName
- @param randomNum
- @param dataPattern
- @return String
*/
public static String generateFileName(String fileName,int randomNum,String dataPattern) {
// 获得当前时间
DateFormat format = new SimpleDateFormat(dataPattern);
// 转换为字符串
String formatDate = format.format(new Date());
// 随机生成文件编号
int random = new Random().nextInt(randomNum);
// 获得文件后缀名称
int position = fileName.lastIndexOf(".");
String extension = fileName.substring(position);
// 组成一个新的文件名称
return formatDate + random + extension;
}
/**
*- @Title: countFileSize
- @Description: 根据File文件的长度统计文件的大小
- @param fileSize
- @return String
*/
public static String countFileSize(long fileSize) {
String fileSizeString = "";
try {
DecimalFormat df = new DecimalFormat("#.00");
long fileS = fileSize;
if (fileS == 0) {
fileSizeString = "0KB";
} else if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1073741824) {
fileSizeString = df
.format(((double) fileS / 1024 / 1024) - 0.01)
+ "MB";
} else {
fileSizeString = df.format((double) fileS / 1024 / 1024 / 1024)
+ "G";
}
} catch (Exception e) {
e.printStackTrace();
}
return fileSizeString;
}
/**
*- @Title: conversionSpecialCharacters
- @Description: 把两个反斜线转换成正斜线
- @param string
- @return String
*/
public static String conversionSpecialCharacters(String string) {
return string.replaceAll("\\", "/");
}
public static void main(String[] args) {
}
}`

浙公网安备 33010602011771号