java post 文件上传

java post 文件上传

package upload;

import com.loop.core.modules.kit.RandomKit;
import org.junit.Test;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by IntelliJ IDEA.
 * Author: kid 86883772@qq.cm
 * Description: 文件上传
 * Date:2016/12/20.
 * Time:9:38.
 */
public class FileUpload {
    @Test
    public void uploadTest() {
        String res = uploadImage("http://wechat.kid.be-xx.com/kidtest/upload", new File("C:\\Users\\Haitao\\Desktop\\t\\t2.jpg"), (System.currentTimeMillis()) + ".jpg");
        System.out.println("Res:" + res);
    }

    public String uploadImage(String url, File file, String fileName) {
        String res = "";
        try {
            URL u = new URL(url);
            URLConnection conn = u.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            String split = "--";
            String boundary = getBoundary();
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            OutputStream outputStream = new DataOutputStream(conn.getOutputStream());
            StringBuffer imageData = new StringBuffer();
            imageData.append("\r\n").append(split).append(boundary).append("\r\n");
            imageData.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"").append("\r\n");
            imageData.append("Content-Type:image/png");
            imageData.append("\r\n\r\n");
            outputStream.write(imageData.toString().getBytes());
            //读取文件信息
            readFile(outputStream, file);
            byte[] endData = ("\r\n" + split + boundary + split + "\r\n").getBytes();
            outputStream.write(endData);
            outputStream.flush();
            outputStream.close();
            res = InputStreamToString(conn.getInputStream());
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            return res;
        }
    }

    private void readFile(OutputStream outputStream, File file) throws IOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = fis.read(b)) != -1) {
                outputStream.write(b, 0, len);
            }
        } catch (IOException io) {
            throw io;
        } finally {
            if (null != fis) {
                fis.close();
            }
        }
    }


    private String getBoundary() {
        return RandomKit.ice.getRandomOfLetterAndNumber(32, true);
    }


    private String InputStreamToString(InputStream inputStream) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        boolean firstLine = true;
        try {
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                if (!firstLine) {
                    stringBuilder.append(System.getProperty("line.separator"));
                } else {
                    firstLine = false;
                }
                stringBuilder.append(line);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            return stringBuilder.toString();
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值