java实现文件上传接口及java调用文件上传接口

/**
 * 调用流程上传文件接口上传文件
 * @param path
 * @return
 */
public String sendPostUplodFile(String path) {
    DataOutputStream out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(uploadPic + "?caseId=klxxxxxx");
        //打开和URL之间的连接
        HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
        //发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);

        String BOUNDARY = "----WebKitFormBoundary07I8UIuBx6LN2KyY";
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        conn.connect();

        out = new DataOutputStream(conn.getOutputStream());
        byte[] end_data = ("
--" + BOUNDARY + "--
").getBytes();
        //添加参数
        StringBuffer sb1 = new StringBuffer();
        sb1.append("--");
        sb1.append(BOUNDARY);
        sb1.append("
");
        sb1.append("Content-Disposition: form-data;name="luid"");
        sb1.append("
");
        sb1.append("
");
        sb1.append("123");
        sb1.append("
");
        out.write(sb1.toString().getBytes());
        //添加参数file
        File file = new File(path);
        StringBuffer sb = new StringBuffer();
        sb.append("--");
        sb.append(BOUNDARY);
        sb.append("
");
        sb.append("Content-Disposition: form-data;name="file";filename="" + file.getName() + """);
        sb.append("
");
        sb.append("Content-Type: application/octet-stream");
        sb.append("
");
        sb.append("
");
        out.write(sb.toString().getBytes());

        DataInputStream in1 = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in1.read(bufferOut)) != -1) {
            out.write(bufferOut,0,bytes);
        }
        out.write("
".getBytes());
        in1.close();
        out.write(end_data);

        //flush输出流的缓冲
        out.flush();
        //定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return result;
}
/**
     * 文件上传保存接口
     * @param request
     * @param caseId
     * @return
     * @throws IOException
     */
    public Json upload(HttpServletRequest request, String caseId) throws IOException {
        String oper = "/file/upload";
        if (StringUtils.isEmpty(caseId)) {
            return Json.fail(oper, "参数错误");
        }
        MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest) request;
        //得到文件map对象
        Map<String, MultipartFile> files = Murequest.getFileMap();
        System.out.println("files ========" + files.toString());
        List<TabCaseMaterial> list = new ArrayList<>();
        for (MultipartFile file : files.values()) {
            file.getSize();
            //获取文件名
            String fileName = file.getOriginalFilename();
            System.out.println("上传的文件名为:" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String newfileName = UUID.randomUUID().toString() + suffixName;  //完全替换文件名称 2020-07-17
            System.out.println("newfileName =" + newfileName);
            StringBuilder sb = new StringBuilder(newfileName);
            //创建文件对象
            File tagetFile = new File(physicpath + File.separator + caseId + File.separator + sb.toString());
            // 如果上传文件夹不存在则创建
            if (!tagetFile.getParentFile().exists() && !tagetFile.isDirectory()) {
                tagetFile.getParentFile().mkdirs();
                tagetFile.createNewFile();
            } else if (!tagetFile.exists()) {
                tagetFile.createNewFile();
            }
            try {
                file.transferTo(tagetFile);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String backUrl = "";
            backUrl = tomcatpath + "/" + caseId + "/" + newfileName;

            System.out.println("backUrl ==== " + backUrl);
            TabCaseMaterial material = new TabCaseMaterial();
            material.setOriName(fileName.substring(0, fileName.lastIndexOf(".")));
            material.setFileName(newfileName);
            material.setFileUrl(backUrl);
            list.add(material);
        }
        return Json.succ(oper, list);
    }
原文地址:https://www.cnblogs.com/Anonyme/p/14669682.html