当前位置: 代码迷 >> Web前端 >> servlet 下传文件
  详细解决方案

servlet 下传文件

热度:139   发布时间:2012-11-22 00:16:41.0
servlet 上传文件

原文:http://zhidao.baidu.com/question/263826186.html

?

public String uploadFile(HttpServletRequest request){
		
		try {
			
		DiskFileItemFactory factory= new DiskFileItemFactory();
		ServletFileUpload upload= new ServletFileUpload(factory);
		List<FileItem>  list = upload.parseRequest(request);
		String encoding=request.getCharacterEncoding();
		upload.setHeaderEncoding(encoding);
		upload.setFileSizeMax(fileMaxSize);
		for(FileItem  fileItem : list){
			String fileName = fileItem.getFieldName();
			if(fileItem.isFormField()){
				if("send".equals(fileName)){
				   edto.setSend(fileItem.getString(encoding));
				}
				if("incept".equals(fileName)){	
				edto.setIncept(fileItem.getString(encoding));
				}
				if("theme".equals(fileName)){
				edto.setTheme(fileItem.getString(encoding));
				}
				if("letter".equals(fileName)){
					edto.setLetter(fileItem.getString(encoding));
				}
			}
			else{
				if("file".equals(fileName)){
					String sourceFilePath = fileItem.getName();
					if(sourceFilePath!=""){
					if(fileItem.getSize()>fileMaxSize){
						return "文件过大,不能上传!";
					}
					HttpSession session =request.getSession();
					String serverPath = session.getServletContext().getRealPath("");
					String savePath = serverPath + "\\userfile";
					String saveFileName =GetSaveFileName.getFileName(edto.getIncept(),edto.getSend(),sourceFilePath);
					InputStream in = fileItem.getInputStream();
					edto.setSaveFileName(saveFileName);

					this.saveFile(savePath,saveFileName, in);
					
					}	
				}	
			}		
		}

保存上传的文件到服务器:
//保存文件到服务器
	private  void saveFile(String savePath,String saveFileName,InputStream in) throws IOException{
		
		File file=new File(savePath);
		
		if(!file.exists()){
			file.mkdirs();
		}
		
		FileOutputStream out =new FileOutputStream(savePath+"\\"+saveFileName);
		
		byte [] b =new byte[1024];
		
		int len = in.read(b);
		
		 while(len!=-1){
			out.write(b, 0, len);
			out.flush();
			len = in.read(b);
		}
		 out.close();
		 in.close();
	}
?

?

?

  相关解决方案