• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

java文件上传,实现不同服务器:间文件的传输,HttpClient发送,fileupload接收

武飞扬头像
qq_34297581
帮助1

  1. 客户端,利用HttpClient发送
    首先导入依赖:
<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.13</version>
        </dependency>

客户端推送代码:

public class HttpSendFile {

    /**
     * HttpClient调用文件发送接口
     * @param file  上传的文件
     * @return
     */

    public static Map<String, Object> call_sendFile(File file){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        Map<String, Object> responseMap = new HashMap<>();
        String result="";
        try{
            //服务端地址,为了测试直接写死,换成你们自己的
            HttpPost httpPost = new HttpPost("http://localhost:8277/xxxx/fileReceive");

            //创建接口需要的参数
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            ContentType infoCType = ContentType.create("application/json", "UTF-8");
            ContentType fileCType = ContentType.create("application/octet-stream", "UTF-8");
            entityBuilder.addPart("file", new FileBody(file, fileCType));
            entityBuilder.addPart("filepath", new StringBody("filepath123", infoCType));
            HttpEntity entity = entityBuilder.build();
            httpPost.setEntity(entity);

            //调用跨网文件发送接口
            HttpResponse response = httpclient.execute(httpPost);
            //获取响应信息
            HttpEntity responseEntity = response.getEntity();
            if(responseEntity != null){
                result = EntityUtils.toString(responseEntity, "UTF-8");
            }
            responseMap.put("code", response.getStatusLine().getStatusCode());
            responseMap.put("result", result);
        } catch (IOException e){
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        return responseMap;
    }

}
学新通
  1. 服务端代码
    首先导入依赖:
<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>

服务器代码(非springboot框架),利用继承HttpServlet实现一个servlet:

public class FileReceiveServ extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 1.创建磁盘文件工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 2.创建文件上传类的对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 2.1设置文件上传的编码
            upload.setHeaderEncoding("utf-8");
            // 2.2判断表单是否是多部件文件上传的表单
            boolean multipartContent = upload.isMultipartContent(req);
            System.out.println("表单是否是多部件文件上传表单"   multipartContent);
            // 2.3如果是多部件文件上传表单
            if (multipartContent) {
                // 3.开始解析请求,获取多部件文件上传表单的集合,集合中存储的是每一个表单项
                List<FileItem> list = upload.parseRequest(req);
                if (null != list) {
                    // 4.遍历件上传表单项集合
                    for (FileItem item : list) {
                        // 5.判断是普通表单项还是文件上传表单项
                        boolean formField = item.isFormField(); // 该方法判断是否是普通表单项
                        if (formField) {
                            // 普通表单项, 当 enctype="multipart/form-data"时, request的getParameter()方法 无法获取参数
                            String fieldName = item.getFieldName(); // 获取表单文本框中name的属性值
                            String value = item.getString("utf-8"); // 获取utf-8编码之后表单文本框中的内容
                            System.out.println(fieldName   " = "   value);
                        } else {
                            // 文件上传表单项
                            String fileName = item.getName();   // 获取文件名
                            //获取文件对象
                            File file = new File("E:\\12306", fileName);
                            // 写文件对象
                            item.write(file);
                        }
                    }
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
学新通

web.xml的配置此servlet

<servlet>
		<servlet-name>fileReceive</servlet-name>
		<servlet-class>com.hits.modules.sys.FileReceiveServ</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>fileReceive</servlet-name>
		<url-pattern>/fileReceive</url-pattern>
	</servlet-mapping>
  1. 写个controller进行测试
@Controller
public class FileSendController {
    @RequestMapping("/sendFile")
    public void receiveFile(HttpServletRequest req, HttpServletResponse resp){
        HttpSendFile.call_sendFile(new File("D:\\gongju","ceshi.doc"));
    }
}

请求地址进行测试
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgcccic
系列文章
更多 icon
同类精品
更多 icon
继续加载