您的位置:首页 > 其它

servlet上传和文件转成流

2015-12-30 18:48 453 查看
import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

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;
import org.apache.commons.lang3.StringUtils;

public class FileUpload {

/**
*
* @Title: upload
* @Description: TODO(文件上传保存的本地,可同时上传多个文件)
* @param @param request
* @param @param savePath    文件要保存的路径
* @param @param tempPath    文件上传时的缓存路径
* @param @return
* @param @throws FileUploadException
* @param @throws IOException 设定文件
* @return ArrayList<HashMap> HashMap中 包含oldName(文件上传时的名称),newName(文件保存在服务器的名称),savePath(文件保存路径)
* @throws AppException
* @throws
* @author liubf
* @date 2015年12月28日 上午11:01:12
*/
public static ArrayList<HashMap> upload(HttpServletRequest request,String savePath,String tempPath)
throws FileUploadException, IOException, AppException {
ArrayList<HashMap> saveInfoList = new ArrayList<HashMap>();//保存上传文件信息
SimpleDateFormat DateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
String timeStr = DateFormat.format(new Date());
File repository = new File(tempPath);//缓存文件
//创建一个磁盘文件工厂
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(5*1024*1024, repository);//缓存大小为5M
ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
fileUpload.setSizeMax(10*1024*1024);//设置上传文件的大小
fileUpload.setHeaderEncoding("utf-8");//设置编码
try {
List<FileItem> fileList = fileUpload.parseRequest(request);
for(FileItem item : fileList){
HashMap<String, Object> fileInfoMap = new HashMap<String,Object>();
if(item.isFormField()){//如果是表单数据,暂不处理
request.setAttribute(item.getFieldName(), item.getString("utf-8"));//如果你页面编码是utf-8的

}else{//如果是文件
String fileName = item.getName();//上传时文件的名称
if(StringUtils.isEmpty(fileName)){
throw new AppException("上传文件不能为空!");
}
int index = fileName.lastIndexOf("\\");
if(-1 != index    ){
fileName = fileName.substring(index+1);
}
InputStream inputStream = item.getInputStream();//输入流
Random random = new Random();
String saveName = timeStr+random.nextInt(10000)+fileName.substring(fileName.lastIndexOf("."));//文件保存的名字
File fileDir = new File(savePath);
fileDir.mkdirs();
File saveFile = new File(fileDir, saveName);
FileOutputStream outputStream = new FileOutputStream(saveFile);
// 输入流转换成输出流输出到本地文件
int len = 0;
byte[] b = new byte[1024];
while((len = inputStream.read(b))!=-1){
outputStream.write(b, 0, len);
}
inputStream.close();
outputStream.close();
//添加上传文件的信息以返回
fileInfoMap.put("oldName", fileName);
fileInfoMap.put("newName", saveName);
fileInfoMap.put("savePath", savePath+"/"+saveName);
fileInfoMap.put("suffix", fileName.substring(fileName.lastIndexOf(".")));
saveInfoList.add(fileInfoMap);
}
item.delete();
}
} catch (FileUploadException e) {
System.out.println("文件上传时发生错误!错误原因:" +e.getMessage());
throw e;
} catch (IOException e) {
System.out.println("读取文件信息时发生错误!错误原因:" +e.getMessage());
throw e;
}
return saveInfoList;
}

/**
*
* @Title: fileToStream
* @Description: TODO(上传文件转换成输入流流,一次仅可以上传一个文件)
* @param @param request
* @param @param tempPath    文件缓存路径
* @param @return
* @param @throws IOException 设定文件
* @return ArrayList<HashMap> HashMap中 包含oldName(文件上传时的名称),inputStream(文件转换为输入流),suffix(文件后缀名)
* @throws AppException
* @throws FileUploadException
* @throws
* @author liubf
* @date 2015年12月28日 上午11:04:25
*/
public static HashMap<String, Object> fileToStream(HttpServletRequest request,String tempPath)
throws Exception {
InputStream inputStream = null;
HashMap<String, Object> resultMap = new HashMap<String, Object>();
File repository = new File(tempPath);//缓存文件
//创建一个磁盘文件工厂
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(5*1024*1024, repository);//缓存大小为5M
ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
fileUpload.setSizeMax(10*1024*1024);//设置上传文件的大小
fileUpload.setHeaderEncoding("utf-8");//设置编码
try {
List<FileItem> fileList = fileUpload.parseRequest(request);
short fileSum = 0;
for(FileItem item : fileList){
HashMap<String, Object> fileInfoMap = new HashMap<String,Object>();
if(item.isFormField()){//如果是表单数据,暂不处理
}else{//如果是文件
fileSum++;
String fileName = item.getName();
if(StringUtils.isEmpty(fileName)){
throw new AppException("上传文件不能为空!");
}
int index = fileName.lastIndexOf("\\");
if(-1 != index    ){
fileName = fileName.substring(index+1);
}
inputStream = item.getInputStream();//输入流
resultMap.put("oldName", fileName);
resultMap.put("inputStream", inputStream);
resultMap.put("suffix", fileName.substring(fileName.lastIndexOf(".")));
}
item.delete();
if(fileSum>1){
throw new AppException("上传的文件不能多于一个!");
}
}
} catch (FileUploadException e) {
e.printStackTrace();
System.out.println("读取文件信息时发生错误!");
throw e;
}
return resultMap;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: