java 模拟http文件上传,HttpURLConnection上传多文件

public static String sendFile(final String url, byte[] file, String filename) throws Exception{
        final String boundary = "===" + Long.toHexString(System.currentTimeMillis()) + "===";//分割线
        final String CRLF = "\r\n";
        HttpURLConnection httpConn = null;
        try {
            httpConn = (HttpURLConnection) new URL(url).openConnection();
            httpConn.setConnectTimeout(5 * 1000);
            httpConn.setRequestProperty("Connection", "close");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setUseCaches(false);
            httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            httpConn.connect();
            try (
                    OutputStream output = httpConn.getOutputStream();
                    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true)
            ) {
                writer.append("--" + boundary)
                        .append(CRLF)
                        .append("Content-Disposition: form-data; name=file; filename=" + filename)
                        .append(CRLF)
                        .append(
                                new StringBuilder("Content-Type:")
                                        .append( URLConnection.guessContentTypeFromName(filename) )
                                        .append("; charset=UTF-8")
                        )
                        .append(CRLF)
                        .append("Content-Transfer-Encoding: binary")
                        .append(CRLF)
                        .append(CRLF)
                        .flush();
                output.write(file);
                output.flush();
                writer.append(CRLF)
                        .flush();
                writer.append("--" + boundary + "--")
                        .append(CRLF)
                        .flush();
                //http1.1是半双工模式,必须写完成之后再拿服务端的inputStream
                try (InputStream inputStream = httpConn.getInputStream()){
                    byte[] resByte = new byte[ inputStream.available() ];
                    inputStream.read(resByte);
                    String res = new String(resByte);
                    System.out.println(res);
                    return res;
                }
            }
        } finally {
            if (httpConn != null){
                httpConn.disconnect();
            }
        }
    }

main方法进行测试:

  public static void main(String[] args) throws Exception {
        FileChannel fileChannel = FileChannel.open( Paths.get("B:\\documents\\mycat.pdf") );
        ByteBuffer byteBuffer = ByteBuffer.allocate( (int) fileChannel.size() );
        fileChannel.read(byteBuffer);
        sendFile("http://localhost:8097/api/save", byteBuffer.array(), "mycat-pdf");
    }

springmvc后端接口接收:

@RequestMapping(value = "/save", method = RequestMethod.POST)
	public LllFile save(@RequestParam(name = "file") MultipartFile multipartFile, String filename, String usrId, String acct){
		try{
			byte[] file = multipartFile.getBytes();
			LllFile res = iFileService.saveFile(file, filename, usrId, acct);
			return res;
		}catch(Exception ex){
			log.error("", ex);
		}
		
		return null;
	}

纯servlet接收,通过request的getPart方法:

@RequestMapping(value = "/save", method = RequestMethod.POST) 
public LllFile save(HttpServletRequest request) throws IOException, ServletException {
        Collection<Part> parts = request.getParts();
        for (Part part : parts) {
            System.out.println(part.getSize());
            System.out.println("文件名:" + part.getSubmittedFileName());
        }
return null;
}

上传多个文件:

1:首先查看浏览器是怎么区分多文件的;

-----Webkit***是chrome用来区分文件的,最后一个boundary后面多了个--。

java实现如下:

 public static String sendMultipleFile(Map<String, byte[]> fileMsgMap, final String url) throws Exception {
        final String boundary = "===" + Long.toHexString(System.currentTimeMillis()) + "===";//分割线
        final String CRLF = "\r\n";
        HttpURLConnection httpConn = null;
        try {
            httpConn = (HttpURLConnection) new URL(url).openConnection();
            httpConn.setConnectTimeout(5 * 1000);
            httpConn.setRequestProperty("Connection", "close");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setUseCaches(false);
            httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            httpConn.connect();
            try (
                    OutputStream output = httpConn.getOutputStream();
                    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true)
            ) {
                for (Map.Entry<String, byte[]> entry : fileMsgMap.entrySet()) {
                    writer.append("--" + boundary)
                            .append(CRLF)
                            .append("Content-Disposition: form-data; name=files; filename=" + entry.getKey())
                            .append(CRLF)
                            .append(
                                    new StringBuilder("Content-Type:")
                                            .append( URLConnection.guessContentTypeFromName(entry.getKey()) )
                                            .append("; charset=UTF-8")
                            )
                            .append(CRLF)
                            .append("Content-Transfer-Encoding: binary")
                            .append(CRLF)
                            .append(CRLF)
                            .flush();
                    output.write(entry.getValue());
                    output.flush();
                    writer.append(CRLF)
                            .flush();
                }
                //最后一行末尾多个--
                writer.append("--" + boundary + "--")
                        .append(CRLF)
                        .flush();
                //http1.1是半双工模式,必须写完成之后再拿服务端的inputStream
                try (InputStream inputStream = httpConn.getInputStream()){
                    byte[] resByte = new byte[ inputStream.available() ];
                    inputStream.read(resByte);
                    String res = new String(resByte);
                    System.out.println(res);
                    return res;
                }
            }
        } finally {
            if (httpConn != null){
                httpConn.disconnect();
            }
        }
    }

springmvc接收代码:

   @PostMapping(path = "/up")
    @ResponseBody
    public String upFile(@RequestParam(name = "files") MultipartFile[] multipartFiles, HttpServletRequest request) throws IOException, ServletException {
//        Collection<Part> parts = request.getParts();
//        for (Part part : parts) {
//            System.out.println(part.getSize());
//            System.out.println("文件名:" + part.getSubmittedFileName());
//        }
        System.out.println(multipartFiles);
        System.out.println(multipartFiles.length);
        for (MultipartFile file : multipartFiles) {
            System.out.println("文件名是:" + file.getOriginalFilename());
            System.out.println("文件信息大小是:" + file.getBytes().length);
        }
        return "ok";
    }

上传多个文件最好修改tomcat的最大post请求大小限制,

server:
  tomcat:
    max-http-form-post-size: 40MB

或者

server:
    tomcat:
      #30Mb最大post请求体
      max-http-post-size: 31457280
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值