01 上传文件

  • 上传文件代码
/** 
     * 传输文件
     * @param fileName 文件名
     * @param path 文件路径
     * @param url 上传接口
     * @return
     */ 
public static String UploadFileByHttpClient(String fileName,String path, String url) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            //HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            httpPost.addHeader("header1", "111");//头部放文件上传的head可自定义
            File file = new File(path+fileName); //上传文件的路径 
            builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, fileName);
            builder.addTextBody("params1", "1");//其余参数,可自定义
            builder.addTextBody("params2", "2");
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();//接收调用外部接口返回的内容
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            // 返回的内容都在content中
            InputStream content = responseEntity.getContent();
            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println(result);
            
        }
        }catch(Exception e) {
        }finally {//处理结束后关闭httpclient的链接
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
         
        return result;
    }
  • springMvc接收接口
@RequestMapping("getFileByIo.do")
    public void getFileByIo(
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletResponse response, HttpServletRequest request)
            throws Exception {
        String fileName = file.getOriginalFilename();
        System.out.println("文件名------>"+fileName+"文件大小"+file.getSize());
        String path="D:/xtyx3/"+new Date().getTime()+file.getOriginalFilename();
        file.transferTo(new File(path));
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(fileName);
        out.flush();
        out.close();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值