您的位置:首页 > 理论基础 > 计算机网络

java、 http模拟post上传文件到服务端 模拟form上传文件

2018-03-08 10:46 513 查看
需求是这样的:

**1,前后端分离,前端对接pc软件进行文件同步的接口,后的springboot微服务进行文件接收和处理。

2,软件不能直接调用微服务的接口进行上传,只能先走一下前端controller进行转发过来()。

3,这样就只能用httpclient进行http的转发请求,先把文件上传来放到本地临时处理下,在转到微服务端进行处理。

4,post方式传输,单纯的字符参数好处理,单纯的文件也能处理,2个都存在,会有一些小问题,尤其是报文那里。**

第一步:同步文件的接口

@ResponseBody
@RequestMapping(value="/res/upload",method=RequestMethod.POST, produces = "text/html;charset=UTF-8")
public String softUpload(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
MultipartFile dataFile = request.getFile("file");
String userName = request.getParameter("userName");
String token = request.getParameter("token");
String fileName = dataFile.getOriginalFilename();
String ext = fileName.substring(fileName.lastIndexOf("."));
String saveFileName = "";
String relativePath = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
relativePath = sdf.format(new Date()) + File.separator + UUID.randomUUID().toString().replace("-", "");
saveFileName = Configuration.getDataPath() + "/" + relativePath + ext;
// 将文件保存起来
FileUtils.writeByteArrayToFile(new File(saveFileName), dataFile.getBytes());
String doPost = HttpUtils.doPostWithFile(url, saveFileName,fileName,userName);
return doPost;
}


第二部:模拟post传输工具类

/**
* 提交file模拟form表单
* @param url
* @param savefileName
* @param fileName
* @param param
* @return
*/
public static String doPostWithFile(String url,String savefileName,String fileName, String param) {
String result = "";
try {
// 换行符
final String newLine = "\r\n";
final String boundaryPrefix = "--";
// 定义数据分隔线
String BOUNDARY = "========7d4a6d158c9";
// 服务器的域名
URL realurl = new URL(url);
// 发送POST请求必须设置如下两行
HttpURLConnection connection = (HttpURLConnection) realurl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("Charset","UTF-8");
connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
// 头
String boundary = BOUNDARY;
// 传输内容
StringBuffer contentBody =new StringBuffer("--" + BOUNDARY);
// 尾
String endBoundary ="\r\n--" + boundary + "--\r\n";

// 1. 处理普通表单域(即形如key = value对)的POST请求(这里也可以循环处理多个字段,或直接给json)
//这里看过其他的资料,都没有尝试成功是因为下面多给了个Content-Type
//form-data  这个是form上传 可以模拟任何类型
contentBody.append("\r\n")
.append("Content-Disposition: form-data; name=\"")
.append("param" + "\"")
.append("\r\n")
.append("\r\n")
.append(param)
.append("\r\n")
.append("--")
.append(boundary);
String boundaryMessage1 =contentBody.toString();
System.out.println(boundaryMessage1);
out.write(boundaryMessage1.getBytes("utf-8"));

// 2. 处理file文件的POST请求(多个file可以循环处理)
contentBody = new StringBuffer();
contentBody.append("\r\n")
.append("Content-Disposition:form-data; name=\"")
.append("file" +"\"; ")   // form中field的名称
.append("filename=\"")
.append(fileName +"\"")   //上传文件的文件名,包括目录
.append("\r\n")
.append("Content-Type:multipart/form-data")
.append("\r\n\r\n");
String boundaryMessage2 = contentBody.toString();
System.out.println(boundaryMessage2);
out.write(boundaryMessage2.getBytes("utf-8"));

// 开始真正向服务器写文件
File file = new File(savefileName);
DataInputStream dis= new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut =new byte[(int) file.length()];
bytes =dis.read(bufferOut);
out.write(bufferOut,0, bytes);
dis.close();
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();

// 4. 从服务器获得回答的内容
String strLine="";
String strResponse ="";
InputStream in =connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while((strLine =reader.readLine()) != null)
{
strResponse +=strLine +"\n";
}
System.out.print(strResponse);
return strResponse;
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
return result;
}


第三部:服务接收端 处理文件file

//新建资源这个是springboot接口
@RequestMapping(value = "/upload",method =RequestMethod.POST)
public ReturnResult<?> uploadRes( MultipartFile file, String param)throws Exception;

//这里@RequestPart 注解直接接受file就可以了
public ReturnResult<?> uploadRes(@RequestPart("file") MultipartFile file,@RequestParam("param") String name) throws Exception{
logger.info("****新建资源****");

//处理逻辑

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐