public
void
doGet(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
try
{
System.out.println(
"IP:"
+ request.getRemoteAddr());
DiskFileItemFactory facotry =
new
DiskFileItemFactory();
String tempDir = getServletContext().getRealPath(
"/WEB-INF/temp"
);
facotry.setRepository(
new
File(tempDir));
ServletFileUpload upload =
new
ServletFileUpload(facotry);
upload.setHeaderEncoding(
"UTF-8"
);
upload.setFileSizeMax(
1024
*
1024
*
1024
);
upload.setSizeMax(
2048
*
1024
*
1024
);
boolean
bb = upload.isMultipartContent(request);
if
(!bb) {
return
;
}
List<FileItem> items = upload.parseRequest(request);
String storePath = getServletContext().getRealPath(
"/WEB-INF/upload"
);
for
(FileItem item : items) {
if
(item.isFormField()) {
String fieldName = item.getFieldName();
String fieldValue = item.getString(
"UTF-8"
);
System.out.println(fieldName +
"="
+ fieldValue);
}
else
{
String fileName = item.getName();
if
(fileName==
null
||fileName.trim().equals(
""
)){
continue
;
}
fileName = fileName
.substring(fileName.lastIndexOf(
"\\"
) +
1
);
String newFileName = UUIDUtil.getUUID() +
"_"
+ fileName;
System.out.println(
"上传的文件名是:"
+ fileName);
InputStream in = item.getInputStream();
String savePath = makeDir(storePath, fileName) +
"\\"
+ newFileName;
OutputStream out =
new
FileOutputStream(savePath);
byte
b[] =
new
byte
[
1024
];
int
len = -
1
;
while
((len = in.read(b)) != -
1
) {
out.write(b,
0
, len);
}
in.close();
out.close();
item.delete();
}
}
}
catch
(FileUploadBase.FileSizeLimitExceededException e){
request.setAttribute(
"message"
,
"单个文件大小不能超出5M"
);
request.getRequestDispatcher(
"/message.jsp"
).forward(request,
response);
}
catch
(FileUploadBase.SizeLimitExceededException e){
request.setAttribute(
"message"
,
"总文件大小不能超出7M"
);
request.getRequestDispatcher(
"/message.jsp"
).forward(request,
response);
}
catch
(Exception e) {
e.printStackTrace();
request.setAttribute(
"message"
,
"上传失败"
);
request.getRequestDispatcher(
"/message.jsp"
).forward(request,
response);
}
}
private
String makeDir(String storePath, String fileName) {
int
hashCode = fileName.hashCode();
int
dir1 = hashCode &
0xf
;
int
dir2 = (hashCode &
0xf0
) >>
4
;
String path = storePath +
"\\"
+ dir1 +
"\\"
+ dir2;
File file =
new
File(path);
if
(!file.exists())
file.mkdirs();
return
path;
}
public
void
doPost(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
doGet(request, response);
}