文件的上传下载

346 阅读2分钟

1.根据地址获取文件

/**
	 * 根据地址获取文件
	 * @param listURL
	 * @return
	 */

	public static File getNetUrlHttp(List listURL) {
		String netUrl = (String) listURL.get(0);
		//对本地文件命名
		String fileName = (String) listURL.get(1);
		File file = null;

		URL urlfile;
		InputStream inStream = null;
		OutputStream os = null;
		try {
			file = File.createTempFile("net_url", fileName);
			//下载
			urlfile = new URL(netUrl);
			inStream = urlfile.openStream();
			os = new FileOutputStream(file);

			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
		} catch (Exception e) {
			log.error("图片获取错误:"+netUrl);
			e.printStackTrace();
		} finally {
			try {
				if (null != os) {
					os.close();
				}
				if (null != inStream) {
					inStream.close();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return file;
	}

2.根据文件获取MD5值

	public static String getMD5(File file) {
        FileInputStream fis = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            fis = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length = -1;
            /*System.out.println("开始算");*/
            while ((length = fis.read(buffer)) != -1) {
                md.update(buffer, 0, length);
            }
            /*System.out.println("算完了");*/
            return bytesToString(md.digest());
            } catch (IOException ex) {
             log.error((MD5Util.class.getName()), ex);
                return null;
             } catch (NoSuchAlgorithmException ex) {
            log.error((MD5Util.class.getName()), ex);
             return null;
         } finally {
             try {
                 fis.close();
             } catch (IOException ex) {
                 log.error((MD5Util.class.getName()), ex);
            }
            }
        }
        

3.上传文件至文件服务器

      /**
   * 上传文件至文件服务器
   *
   * @param url        服务器地址
   * @param targetPath 保存路径
   * @param buff       文件二进制
   * @param name       文件名
   * @param urlEncode   是否需要urlencode
   * @return
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static String doPostHSImageUploadFile(String url, String targetPath, byte[] buff, String name, boolean urlEncode) throws ClientProtocolException, IOException {
  	CloseableHttpClient httpClient = HttpClients.createDefault();
  	SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
  	String beginTime = format.format(new Date());
  	String realMd5 = Encryptions.getMD5str(targetPath + beginTime + "com.siit.image.showimage_");
  	String tp = new String(targetPath.getBytes("UTF-8"), "UTF-8");
  	if (urlEncode) {
  		tp = new String(URLEncoder.encode(targetPath, "utf-8").getBytes("UTF-8"), "UTF-8");
  	}
  	try {
  		Header[] headers = {
  				new BasicHeader("targetpath", tp),
  				new BasicHeader("vls", realMd5),
  				new BasicHeader("time", beginTime)
  		};

  		HttpPost httpPost = new HttpPost(url);
  		//设置请求超时时间,4.3后,如果不设置超时时间,默认是24小时
  		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();//设置请求和传输超时时间
  		httpPost.setConfig(requestConfig);

  		//设置一个文件对象参数
  		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  		builder.addBinaryBody("multipartFile", buff, ContentType.create("application/octet-stream"), name);
  		//设置其它参数内容
  		String p = new String(targetPath.getBytes("UTF-8"), "UTF-8");
  		builder.addTextBody("savePath", tp);

  		DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  		String timen = dateformat.format(new Date());
  		builder.addTextBody("time", timen);

  		String iMd5 = Encryptions.getMD5str(timen + p + VAL_ENCODE_KEY);
  		builder.addTextBody("timeMd5", iMd5);
  		builder.setCharset(CharsetUtils.get("UTF-8"));
  		HttpEntity fileEntity = builder.build();
  		httpPost.setEntity(fileEntity);

  		httpPost.setHeaders(headers);
  		// 发起请求 并返回请求的响应
  		CloseableHttpResponse response = httpClient.execute(httpPost);
  		try {
  			// 获取响应对象
  			HttpEntity resEntity = response.getEntity();
  			if (resEntity != null) {
  				JSONObject result = new JSONObject();
  				String mesg = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
  				try {
  					result = JSONObject.fromObject(mesg);
  				} catch (Exception e) {
  					if ("result:1".equals(mesg)) {
  						result.put("result", "1");
  					} else {
  						log.error("返回值格式非JSON格式:" + mesg);
  						result.put("result", "0");
  					}
  				}
  				return result.toString();
  			}
  			// 销毁
  			EntityUtils.consume(resEntity);
  		} catch (Exception ex) {
  			log.error("上传结果解析异常:", ex);
  		} finally {
  			response.close();
  		}
  	} catch (Exception ex) {
  		log.error("上传异常:", ex);
  	} finally {
  		httpClient.close();
  	}
  	return null;
  }

获取UUID:

 String uuid = UUID.randomUUID().toString().replaceAll("-", "");

获取文件后缀名

           String fileType =""
           if(fileFileName.lastIndexOf(".")>0){
                fileType = fileFileName.substring(fileFileName.lastIndexOf(".")+1);
                System.out.println("type::"+fileType);
            }

截取括号中的值

        String st1="aa(sadfjsdkf)";
        int index1 = st1.indexOf('(');
        int index2 = st1.indexOf(')');
        String result = st1.substring(index1 + 1, index2);
        System.out.println(result);

获取年、月、日、时、分

        Calendar calendar = java.util.Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int date = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        System.out.println("年:"+year+">>月:"+month+">>日:"+date+">>时:"+hour+">>分:"+minute);

获取指定的时间格式

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss.SSSSSS");
        String fmDate=simpleDateFormat.format(new Date());

特殊字符 分割的时候使用:

关于点的问题是用 : String.split("[.]"); String.split("\.") ;

关于竖线的问题用 : String.split("\|");

关于星号的问题用 : String.split("\*");

关于斜线的问题用 : Sring.split("\\");