个人图片上传后台程序Servlet

前提需要
commons-fileupload.jar
commons-io.jar
commons-logging.jar


public class PictureUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private Logger log = Logger.getLogger(PictureUploadServlet.class)   ;
	private String image_dir;
	private String image_url;
	private int memory_cache;
	private long max_size;
	private String cache_file;
	private String dir_path;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PictureUploadServlet() {
        try{
    	Properties props = new Properties();
        File f = FileUtil.getFile("classpath:config.properties");
        props.load(new FileInputStream(f));
        image_dir = props.getProperty("Image_dir");
        image_url = props.getProperty("Image_url");
        String maxSize = props.getProperty("maxSize", "3145728");
		max_size = Long.valueOf(maxSize).longValue();
		cache_file = props.getProperty("tempRepository", "d:/pictureupload/temp");		
		String memoryCache = props.getProperty("memoryCache", "4096");
		memory_cache = Integer.valueOf(memoryCache).intValue();
        log.info("PictureUpload init finished.image_dir:"+image_dir);
        log.info("set image_url:"+image_url);
        log.info("set cache file:"+cache_file);
        log.info("set max size:"+max_size);
        log.info("set memory_cache:"+memory_cache);
        checkFile();
        }catch(Exception e){
        	log.error("",e);
        }
    }

	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}

	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset:utf-8");
		PrintWriter out = resp.getWriter();
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(memory_cache);
		factory.setRepository(new File(cache_file));
		
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(max_size);
		//upload.setProgressListener(new FileUploadListener());
		List<FileItem> fileitems = null;
		try {
			fileitems = upload.parseRequest(req);
			log.info("导入文件数量:"+fileitems.size());
		}catch (FileUploadException e) {
			log.error("",e);
			String message = e.getMessage();
			out.write("failed");
			out.flush();
			out.close();
			return;
		}
		this.dir_path = this.image_dir+"/"+DateUtils.getCurrentDateAsString();
		File dir_path_fl = new File(dir_path);
		if(!dir_path_fl.exists()||!dir_path_fl.isDirectory()){
			dir_path_fl.mkdir();
		}
		Iterator<FileItem> item_ite = fileitems.iterator();
		int i=0;
		Image_picture ip = new Image_picture();
		
		while(item_ite.hasNext()){
		    FileItem item = item_ite.next();
		    i++;
		    if(item.isFormField()){
		    	ip = proceedField(item,ip);
		    }else{
		    	ip = proceedFile(item,ip);
		    }
		}
		
		String uuid = DateUtils.getNow().replace(":","").replace(" ","").replace("-","")+UUIDUtil.generateUUID().substring(0,20);
		log.info("picture uuid:"+uuid);
		ip.setUuid(uuid);
		ip.setUrl(image_url+"/"+uuid);
		ip.setCreateddate(DateUtils.parse(DateUtils.getNow()));
		
		ImageUploadService imguserv =WebApplicationContextUtils.getWebApplicationContext(req.getServletContext())
				.getBean("imageUploadService",ImageUploadService.class);
		try{
		imguserv.saveImagePicture(ip);
		}catch(Exception e){
			log.error("",e);
			out.write("failed");
			out.flush();
			out.close();
			return;
		}
	    out.write(ip.getUuid());
	    out.flush();
	    out.close();
	    return;
	}
	/**
	 * 处理文件方法
	 * @param item
	 */
	private Image_picture proceedFile(FileItem item,Image_picture ip){ 
	    log.info("File field name:"+item.getFieldName());
	    log.info("File contenttype:"+item.getContentType());
	    log.info("File size:"+item.getSize());
	    long size = item.getSize();
	    String uuid = UUIDUtil.generateUUID().substring(0,6);
	    String filename = DateUtils.getNow().replace(":","").replace(" ","").replace("-","")+uuid;
	    String uploadname;
	    if(item.getName().lastIndexOf(File.separator)>0){
	    	uploadname = item.getName().substring(item.getName().lastIndexOf(File.separator)+1,item.getName().length());
	    }else{
	    	uploadname = item.getName();
	    }
	    log.info("upload name is :"+uploadname);
	    String filetype = null;
	    if(uploadname.lastIndexOf(".")>0){
	    	filetype = uploadname.substring(uploadname.lastIndexOf(".")+1);
	    }else{
	    	filetype = "";
	    }
	    filename = filename+"."+filetype;
	    log.info("filename is :"+filename);
	    try{
			item.write(new File(dir_path,filename));
		} catch (Exception e) {
			log.error("",e);
		}
	    ip.setFileloc(dir_path+"/"+filename);
	    ip.setSize(size);
	    return ip;
	}
	
	/**
	 * 处理表单字段方法
	 * @param item
	 */
	private Image_picture proceedField(FileItem item,Image_picture ip){
		String fieldname = item.getFieldName();
		String fieldvalue = item.getString();
		if("intx_user".equals(fieldname)){
			log.info("username is:"+fieldname);
		}else if("intx_uploadname".equals(fieldname)){
			try {
				fieldvalue = URLDecoder.decode(fieldvalue,"utf-8");
			} catch (UnsupportedEncodingException e) {
				log.error("",e);
			}
			ip.setPicturename(fieldvalue);
		}else if("se_uploadclassify".equals(fieldname)){
			ip.setClassify(fieldvalue);
		}
		return ip;
	}
	
	/**
	*	检查配置文件存在
	*/		
	private void checkFile(){
		File image_dir_fl = new File(this.image_dir);
		if(!image_dir_fl.exists()||!image_dir_fl.isDirectory()){
			image_dir_fl.mkdirs();
		}
		File cache_file_fl = new File(this.cache_file);
		if(!cache_file_fl.exists()||!cache_file_fl.isDirectory()){
			cache_file_fl.mkdirs();
		}
	}
}



                
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值