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

需求是这样的:
1,前后端分离,前端对接pc软件进行文件同步的接口,后的springboot微服务进行文件接收和处理。
2,软件不能直接调用微服务的接口进行上传,只能先走一下前端controller进行转发过来()。
3,这样就只能用httpclient进行http的转发请求,先把文件上传来放到本地临时处理下,在转到微服务端进行处理。
4,post方式传输,单纯的字符参数好处理,单纯的文件也能处理,2个都存在,会有一些小问题,尤其是报文那里。

  1. 第一步:同步文件的接口
	@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;
	}
  1. 第二部:模拟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";
                //输出
				OutputStream out = connection.getOutputStream();
                // 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;
	}
  1. 第三部:服务接收端 处理文件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("****新建资源****");
		
		//处理逻辑
		
		}
  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
Java可以使用HttpURLConnection类来实现HTTP请求。通过设置请求方法为POST,然后设置Content-Type为multipart/form-data,可以提交文件流到服务。下面是代码示例: ``` URL url = new URL("http://example.com/upload"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream outputStream = conn.getOutputStream(); Writer writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); String fileFieldName = "file"; File fileToUpload = new File("path/to/file"); writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"" + fileFieldName + "\"; filename=\"" + fileToUpload.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileToUpload.getName())).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF); Files.copy(fileToUpload.toPath(), outputStream); writer.append(CRLF).flush(); writer.append("--" + boundary + "--").append(CRLF).flush(); int statusCode = conn.getResponseCode(); ``` 服务可以使用Java Servlet来接收文件流。通过解析HTTP请求中的Content-Type和Content-Disposition头部信息,可以得到发送的文件的信息,然后通过IO流保存上文件。下面是代码示例: ``` Part filePart = request.getPart("file"); InputStream fileContent = filePart.getInputStream(); String fileName = extractFileName(filePart.getHeader("Content-Disposition")); File fileToSave = new File(uploadFilePath + File.separator + fileName); Files.copy(fileContent, fileToSave.toPath()); ``` 其中,extractFileName方法可以解析Content-Disposition头部信息中的文件名: ``` private String extractFileName(String header) { String[] parts = header.split(";"); for (String part : parts) { if (part.trim().startsWith("filename")) { String fileName = part.substring(part.indexOf('=') + 1).trim().replace("\"", ""); return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1); } } return null; } ```
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值