上传下载工具代码

来源:互联网 发布:《大数据时代》 编辑:程序博客网 时间:2024/05/16 01:02
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;}}

原创粉丝点击