Java上传文件到服务器

普通上传文件以下代码就够用了:

/**
     * 上传文件
     * @param urlStr
     * @param file
     */
    public static String upload(String urlStr, File file, String fileName){
        String rv = "";
        try {

            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
            String boundary = "----aryg4pBUG8gGY9qgAAs";

            // 发送POST请求必须设置如下两行  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            conn.setUseCaches(false);  
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            OutputStream out = new DataOutputStream(conn.getOutputStream());  

            StringBuilder sb = new StringBuilder();
            sb.append("--"+boundary);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"media\";filename=\""+ fileName + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");

            //开始
            byte[] data = sb.toString().getBytes();
            out.write(data);

            //将文件写入
            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);
            }
            out.write("\r\n".getBytes());
            in.close();

            //结束分割符
            byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();  
            out.write(end_data);

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

            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sbf = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                sbf.append(line);
            }
            rv = sbf.toString();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rv;
    }

但是如果上面的方式上传不了,返回400,那么就需要使用工具。
典型应用是:SpringMVC中的文件上传就不能用上面的代码,只能使用工具才行。

xUtils是一个github开源项目,封装了发送http请求的细节,也就是干了浏览器发送http请求干的事情。

https://github.com/wyouflf/xUtils

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值