java form 上传文件_Java模拟表单POST上传文件

import java.awt.image.BufferedImage;

import java.awt.image.ColorModel;

import java.io.BufferedReader;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.DataOutputStream;

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.util.Map;

import java.util.concurrent.Callable;

import javax.imageio.IIOImage;

import javax.imageio.ImageIO;

import javax.imageio.ImageTypeSpecifier;

import javax.imageio.ImageWriteParam;

import javax.imageio.ImageWriter;

import org.apache.commons.lang.StringUtils;

import com.grand.mysql_handler.mapper.SystemMapper;

import net.sf.json.JSONObject;

private String uploadImage(String name,byte[] buf) throwsException {

String filename= name.substring(name.lastIndexOf("/") + 1);final String newLine = "\r\n";final String boundaryPrefix = "--";final String boundary = "----theorydance";

String api_url = "http://localhost:8080/filestorage/app/api/fileUpload";

HttpURLConnection conn= (HttpURLConnection) newURL(api_url).openConnection();

conn.setDoInput(true);

conn.setDoOutput(true);

conn.setReadTimeout(20000);

conn.setConnectTimeout(5000);

conn.setRequestMethod("POST");

conn.setRequestProperty("connection", "Keep-Alive");

conn.setRequestProperty("Charset", "UTF-8");

conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" +boundary);

StringBuilder sb= newStringBuilder();//key参数

sb.append(boundaryPrefix + boundary +newLine);

sb.append("Content-Disposition: form-data; name=\"name\"" +newLine);

sb.append(newLine);

sb.append((name==null?"default":name) +newLine);//图片数据

sb.append(boundaryPrefix + boundary +newLine);

sb.append("Content-Disposition: form-data; name=\"myfile\"; filename=\""+filename+"\"" +newLine);

sb.append("Content-Type: application/octet-stream" +newLine);

sb.append(newLine);

OutputStream out= newDataOutputStream(conn.getOutputStream());

out.write(sb.toString().getBytes());

out.write(buf);

out.write(newLine.getBytes());

String endFlag= boundaryPrefix + boundary + boundaryPrefix +newLine;

out.write(endFlag.getBytes());

out.flush();

out.close();

System.out.println("响应状态码:"+conn.getResponseCode());

BufferedReader br= new BufferedReader(newInputStreamReader(conn.getInputStream()));

String line= null;

String content= "";while((line=br.readLine())!=null) {

content+=line;

}

JSONObject json=JSONObject.fromObject(content);

System.out.println(json.toString());return json.getJSONObject("data").getString("url");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值