关闭

上传下载工具代码

501人阅读 评论(0) 收藏 举报
分类:
package com.yym.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;

import javassist.bytecode.stackmap.TypeData.ClassName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UpDownloadUtil {
	
	private static Log log = LogFactory.getLog(UpDownloadUtil.class);
	/**
	* 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应
	* @param url 请求地址 form表单url地址
	* @param fath 文件本地路径
	* @param fileName 文件名称
	* @return String url的响应信息返回值
	* @throws IOException
	*/
	public static String upload(String url,String path,String fileName) throws IOException {
		String result = null;
		File filePath = new File(path);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		File file = new File(filePath, fileName);
		if (!file.exists()) {
			file.createNewFile();
		}
		/**
		* 第一部分
		*/
		URL urlObj = new URL(url);
		// 连接
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

		/**
		* 设置关键值
		*/
		con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false); // post方式不能使用缓存

		// 设置请求头信息
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");

		// 设置边界
		String BOUNDARY = "----------" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);

		// 请求正文信息

		// 第一部分:
		StringBuilder sb = new StringBuilder();
		sb.append("--"); // 必须多两道线
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
		+ file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");

		byte[] head = sb.toString().getBytes("utf-8");

		// 获得输出流
		OutputStream out = new DataOutputStream(con.getOutputStream());
		// 输出表头
		out.write(head);

		// 文件正文部分
		// 把文件以流文件的方式 推入到url中
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();

		// 结尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线

		out.write(foot);

		out.flush();
		out.close();

		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		try {
			// 定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
			//System.out.println(line);
				buffer.append(line);
			}
			if(result==null){
				result = buffer.toString();
			}
		} catch (IOException e) {
			throw new IOException("数据读取异常");
		} finally {
			if(reader!=null){
				reader.close();
			}
			con.disconnect();
		}
		return result;
	}
	/**
	* 
	* @param url 下载url地址
	* @param fath 保存路径
	* @param fileName 文件名称
	* @return String 返回的文件名称
	* @throws IOException
	*/
	public static String download(String urlString, String path, String fileName)
	{
		GZIPInputStream gis = null;
		OutputStream os = null;
		InputStream is = null;
		try
		{
			File filepath = new File(path);
			if (!filepath.exists()) {
				filepath.mkdirs();
			}
			File file = new File(filepath,fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			
			URL url = new URL(urlString);
			URLConnection con = url.openConnection();
			String code = con.getHeaderField("Content-Encoding");
	
			is = con.getInputStream();
			
			if ((null != code) && code.equals("gzip"))
			{
				gis = new GZIPInputStream(is);
				byte[] bs = new byte[1024];
				int len;
				os = new FileOutputStream(file);
				while ((len = gis.read(bs)) != -1)
				{
					os.write(bs, 0, len);
				}
			}
			else
			{
				byte[] bs = new byte[1024];
				int len;
				os = new FileOutputStream(file);
				while ((len = is.read(bs)) != -1)
				{
					os.write(bs, 0, len);
				}
			}
			return file.getName();
		}
		catch (Exception e)
		{
			log.error(ClassName.class,e);
		}
		finally
		{
			try{
				if (gis != null)
					gis.close();
				if (os != null)
				{
					os.flush();
					os.close();
				}
				if (is != null)
					is.close();
			}
			catch(IOException e){
				
			}
			log.info("结束文件传输!");
		}
		return null;
	}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:35962次
    • 积分:854
    • 等级:
    • 排名:千里之外
    • 原创:50篇
    • 转载:11篇
    • 译文:0篇
    • 评论:2条