81,122
社区成员




public ActionForward execute(HttpServletRequest request,
HttpServletResponse reponse) throws Exception {
ActionForward forward = new ActionForward("/fail.go");
HttpSession session = request.getSession();
DiskFileItemFactory dfif = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(dfif);
upload.setSizeMax(5 * 1024 * 1024);
List list = upload.parseRequest(request);
if (list.size() > 0) {
FileItem item = (FileItem) list.get(0);
String name = item.getName();
String path = "/pic/" + name;
// 实现图片上传
item.write(new File(getServletContext().getRealPath(path)));
ActionForward forward = new ActionForward("/success.go");
}
forward.setRedirect(true);
return forward;
}
//存上传的文件
private boolean writeFile(byte[] data, String path) {
File f = null;
FileOutputStream fos = null;
try {
f = new File(path);
f.createNewFile();
fos = new FileOutputStream(f);
fos.write(data, 0, data.length);
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
} finally {
try {
if(fos != null) {
fos.flush();
fos.close();
}
} catch (IOException e) {
return false;
}
}
return true;
}
//取得文件名
private String getFileName(String arg) {
String path = "";
if(arg.equals("\"\"")) {
return null;
}
if (arg.indexOf("\"") > -1)
path = arg.substring(arg.indexOf("\"") + 1, arg.lastIndexOf("\""));
else
path = arg;
path = path.substring(path.lastIndexOf("\\") + 1);
return path;
}
//判断两个byte数组的值是否相等
private boolean arrayEquals(byte[] src, byte[] value){
if(src == null || value == null)
return false;
if(src.length != value.length)
return false;
for(int i=0; i<src.length; i++) {
if(src[i] != value[i])
return false;
}
return true;
}
//找出value数组在src中的位置, 从前往后
private int arrayIndexOf(byte[] src, byte[] value){
if(src == null || value == null)
return -1;
if(src.length < value.length)
return -1;
int postion = -1;
for(int i=0; i<src.length - value.length; i++) {
postion = i;
byte[] tmp = new byte[value.length];
System.arraycopy(src, i, tmp, 0, tmp.length);
if(arrayEquals(tmp, value)) {
tmp = null;
return postion;
}else{
postion = -1;
tmp = null;
}
}
return postion;
}
//找出value数组在src中的位置
private int arrayLastIndexOf(byte[] src, byte[] value){
if(src == null || value == null)
return -1;
if(src.length < value.length)
return -1;
int postion = -1;
for(int i=src.length - value.length ; i >-1; i--) {
postion = i;
byte[] tmp = new byte[value.length];
System.arraycopy(src, i, tmp, 0, tmp.length);
if(arrayEquals(tmp, value)) {
tmp = null;
return postion;
}else{
postion = -1;
tmp = null;
}
}
return postion;
}
private HashMap<String, String> parseAnotherParam(String str){
HashMap<String, String> hm= new HashMap<String, String>();
String key="";
String value="";
int startindex = 0;
int endindex = 0;
startindex = str.indexOf("Content-Disposition: form-data; name=\"")
+ "Content-Disposition: form-data; name=\"".length();
endindex = str.indexOf("\"\r\n\r\n");
while ( startindex >-1 && endindex > -1 ){
key = str.substring(startindex, endindex);
if(!str.substring(endindex , endindex + 5).equals("\"\r\n\r\n") ){//去掉没有value的元素
str = str.substring(endindex);
startindex = str.indexOf("Content-Disposition: form-data; name=\"")
+ "Content-Disposition: form-data; name=\"".length();
endindex = str.indexOf("\"\r\n\r\n");
continue;
}
if( key.indexOf("\";") > -1){//去掉上传文件的参数以及编码
str = str.substring(str.indexOf("\";") + 2);
startindex = str.indexOf("Content-Disposition: form-data; name=\"")
+ "Content-Disposition: form-data; name=\"".length();
endindex = str.indexOf("\"\r\n\r\n");
continue;
} else
str = str.substring(endindex + 5);
value = str.substring(0, str.indexOf("\r\n"));
str = str.substring(str.indexOf("\r\n") + 2);
hm.put(key,value);
startindex = str.indexOf("Content-Disposition: form-data; name=\"")
+ "Content-Disposition: form-data; name=\"".length();
endindex = str.indexOf("\"\r\n\r\n");
}
return hm;
}
}
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.Servlet;
import com.hoperun.e2.util.StringUtil;
@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet implements Servlet{
//允许上传文件的最大M数
public static final int MAX_SIZE = 1024 * 1024 * 100;
//存放上传文件的子目录
private static final String DIR = "UploadFiles/";
//存放运行WEB工程的根路径
private String FILE_DIR;
private int file_Size=0;
private String file_Path = "";
private HashMap<String, String> hm = new HashMap<String, String>();
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) {
doPost(request,response);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) {
String path = this.getServletConfig().getServletContext().getRealPath("/");
FILE_DIR = path.replaceAll("\\\\", "/") + DIR;
String result = upload(request);
PrintWriter out = null;
try {
response.setContentType("text/html;charset=UTF-8");
out = response.getWriter();
out.print(result);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(out != null) {
out.flush();
out.close();
}
}
}
//上传文件
private String upload(HttpServletRequest req) {
String tmpString ="";
String result = "";
DataInputStream dis = null;
try {
dis = new DataInputStream(req.getInputStream());
String content = req.getContentType();
if (content != null && content.indexOf("multipart/form-data") != -1) {
int reqSize = req.getContentLength();
byte[] data = new byte[reqSize];
int bytesRead = 0;
int totalBytesRead = 0;
int sizeCheck = 0;
while (totalBytesRead < reqSize) {
// check for maximum file size violation
sizeCheck = totalBytesRead + dis.available();
if (sizeCheck > MAX_SIZE)
result = "文件太大不能上传...";
bytesRead = dis.read(data, totalBytesRead, reqSize);
totalBytesRead += bytesRead;
}
tmpString = new String(data);
hm = parseAnotherParam(tmpString);
int postion = arrayIndexOf(data, "\r\n".getBytes());
byte[] split_arr = new byte[postion];
System.arraycopy(data, 0, split_arr, 0, postion);
postion = arrayIndexOf(data, "filename=\"".getBytes());
byte[] dataTmp = new byte[data.length - postion];
System.arraycopy(data, postion, dataTmp, 0, dataTmp.length);
data = null;
data = dataTmp.clone();
String filePath =null;
postion = arrayIndexOf(data, "Content-Type:".getBytes())-2;
dataTmp = null;
dataTmp = new byte[postion];
System.arraycopy(data, 0, dataTmp, 0, dataTmp.length);
filePath = new String(dataTmp);
if (filePath==null && filePath.equals("")) return "";
// 分离contentType 并赋值
postion = arrayIndexOf(data, "Content-Type:".getBytes());
dataTmp = null;
dataTmp = new byte[data.length - postion];
System.arraycopy(data, postion, dataTmp, 0, dataTmp.length);
data = null;
data = dataTmp.clone();
postion = arrayIndexOf(data, "\n".getBytes()) + 1;
dataTmp = null;
dataTmp = new byte[data.length - postion];
System.arraycopy(data, postion, dataTmp, 0, dataTmp.length);
data = null;
data = dataTmp.clone();
// 分离文件信息 获得最终想要的字节
postion = arrayIndexOf(data, split_arr);
split_arr = null;
dataTmp = null;
dataTmp = new byte[postion - 2];
System.arraycopy(data, 2, dataTmp, 0, dataTmp.length);
data = null;
data = dataTmp.clone();
postion = arrayLastIndexOf(data, "\n".getBytes())-1;
dataTmp = null;
dataTmp = new byte[postion];
System.arraycopy(data, 0, dataTmp, 0, dataTmp.length);
data = null;
String fileName = getFileName(filePath);
String UUID = StringUtil.makeUUID();
if(null != fileName) {
File file = new File(FILE_DIR);
boolean existsFlag = false;
if(!(existsFlag = file.exists())) {
existsFlag = file.mkdirs();
}
//对文件名做处理,用唯一标识符代替原文件名,后缀名保留
int lastIndex = fileName.lastIndexOf(".");
if(lastIndex == -1) {
fileName = UUID;
} else {
fileName = UUID + fileName.substring(lastIndex, fileName.length());
}
if (writeFile(dataTmp, FILE_DIR + fileName) && existsFlag) {
this.file_Size = dataTmp.length;
this.file_Path = FILE_DIR + fileName;
result = "文件上传完毕." + DIR + fileName;
} else {
result = "文件上传失败";
}
} else {
result = "文件名为空";
}
dataTmp = null;
} else {
result = "content 必须为 multipart/form-data";
}
} catch (UnsupportedEncodingException ex4) {
result = "UnsupportedEncodingException错误";
} catch (NullPointerException e) {
result = "NullPointerException错误";
} catch (IOException ex1) {
result = "IOException 错误 ";
}catch (Exception ex1) {
result = "Exception 错误 ";
} finally {
if(dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}