package com.mage.util;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FilenameUtils;
public class MyFileUploadUtil {
public final static String[] allowFile = {"jpg","bmp","gif","png"};
public final static String PATH = "D:\WorkSpace\20170705\xjau_news_crawler\WebRoot";
public static void uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);// 判断是否是maltipart类型
System.out.println("is Multipart: " + isMultipart);
InputStream is = null;// maltipart类型
FileOutputStream fos = null;
if (isMultipart) {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter;
try {
iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream fis = iter.next();
is = fis.openStream(); // 使用multipart之后就表示通过字节数据进行串联,所以需要转换成数据流
if (fis.isFormField()) { // 如果是表单域
System.out.println("has print field!");
System.out.println(fis.getFieldName()); // isFormFiled 方法判断表是否是普通表单域单域的名称
System.out.println(Streams.asString(is));
} else {
String ext = FilenameUtils.getExtension(fis.getName()); // 得到文件扩展名
boolean b = checkFile(ext);
if (b) {
System.out.println(PATH);
fos = new FileOutputStream(PATH+"/upload/"+fis.getName()); // 传到临时文件夹去了
byte[] buf = new byte[1024];// 缓存
int len = 0; // 输入流用来读,输出流用来写
while((len = is.read(buf))>0){
fos.write(buf, 0, len);
}
}else {
Map<String,String> errors = new HashMap<String, String>();
errors.put("status", "图片类型必须是jpg,bmp,png,gif");
System.out.println("图片类型必须是jpg,bmp,png,gif");
}
}
}
} catch (FileUploadException | IOException e) {
e.printStackTrace();
}finally {
if (is != null) is.close();
if (fos != null) fos.close();
}
}
}
// 检查文件格式是否正确的函数
private static boolean checkFile(String ext) {
for(String s:allowFile) {
if(ext.equals(s)) {
return true;
}
}
return false;
}
}