Skip to content

Instantly share code, notes, and snippets.

@wdfx100
Last active December 16, 2015 06:59
Show Gist options
  • Save wdfx100/5395068 to your computer and use it in GitHub Desktop.
Save wdfx100/5395068 to your computer and use it in GitHub Desktop.
#文件上传#
//commons.apache.org 下的一个组件 upload
//jar:commons-fileupload-1.2.2.jar,依赖jar:commons-io-1.4.jar
<form action="fileUpload" method="post" enctype="multipart/form-data">
文件描述:<input type="text" name="filedesc"><br/>
<input type="file" name="myfile"><br/>
<input type="submit" value="提交"/>
</form>
if(ServletFileUpload.isMultipartContent(request)){//获取请求的方式改变
//创建一个临时文件夹
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File("I:/test/temp"));
//创建一个新文件上传处理程序
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//解析请求,非表单上传元素和表单上传的元素都遍历出来
List<FileItem> items = upload.parseRequest(request);
String filedesc = null;
for(FileItem fileItem : items){
if(fileItem.isFormField()){
//普通表单元素(非file)
if(fileItem.getFieldName().equals("filedesc")){
filedesc = fileItem.getString();
}
System.out.println(fileItem.getFieldName());//filedesc
System.out.println(fileItem.getName());//null
System.out.println(fileItem.getString());//filedesc的值value
}else{
//type为file的表单元素
System.out.println("---------------------------");
System.out.println("Name:"+fileItem.getName());//上传文件的名字
System.out.println("ContentType:"+fileItem.getContentType());//上传文件的格式
System.out.println("Size:"+fileItem.getSize());//上传文件的大小
String fileName = fileItem.getName();
String exeName = fileName.substring(fileName.lastIndexOf("."));
long MaxSize = 1024*1024*3;
if(".jpg".equals(exeName) || ".png".equals(exeName) || ".gif".equals(exeName)){
if(fileItem.getSize()>MaxSize){
response.sendRedirect("toFile?code=1002");
}else{
UUID uuid = UUID.randomUUID();
System.out.println(uuid);
fileName = uuid+exeName;
// 显示上传的文件
File path = new File(getServletContext().getRealPath("/")+"upload");//获得根路径
System.out.println(path);
if(!path.exists()){
path.mkdir();
}
File file = new File(path,fileName);
InputStream inputStream = fileItem.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
int len = -1;
byte[] b = new byte[1024];
while((len=bis.read(b)) != -1){
bos.write(b, 0, len);
}
bos.flush();
bos.close();
bis.close();
request.setAttribute("fileName", fileName);
request.getRequestDispatcher("/WEB-INF/views/showpic.jsp").forward(request, response);
}
}else{
response.sendRedirect("toFile?code=1001");
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}else{
response.sendError(500, "页面访问有错");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment