文件上传,文件损坏

文件上传代码
public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			if(!upload.isMultipartContent(request)){
				//
			}
			List items = upload.parseRequest(request);
			for(FileItem item:items){
				if(item.isFormField()){
					String fieldName = item.getFieldName();
					String fieldValue = item.getString();
					System.out.println("name---"+fieldName+"--value---"+fieldValue);
				}else{
					InputStream in = item.getInputStream();
					String path = request.getServletContext().getRealPath("/WEB-INF/upload");
					File file = new File(path,item.getName());
					FileOutputStream out = new FileOutputStream(file);
					
					int len = 0;
					byte [] buffer = new byte[1024];
					
					while((len=in.read(buffer))>0){//如果这里忘记写buffer,可能会导致文件损坏哦!!
						out.write(buffer,0,len);
					}
					in.close();
					out.close();
					item.delete();
				}
			}
			request.setAttribute("message", "文件上传成功!!!");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("message", "文件上传失败!!!");
		}
		request.getRequestDispatcher("/message.jsp").forward(request,response);
	}


 

你可能感兴趣的:(jsp)