zoukankan      html  css  js  c++  java
  • HttpClient上传文件

    1、上传客户端代码:

    public static void upload() {  
            CloseableHttpClient httpclient = HttpClients.createDefault();  
            try {  
                HttpPost httppost = new HttpPost("http://172.18.5.107:90/Download.html");  
                FileBody bin = new FileBody(new File("D:\BaiduNetdiskDownload\背景圖\b.jpg")); 
                FileBody bin2 = new FileBody(new File("D:\BaiduNetdiskDownload\背景圖\哈哈哈.jpg")); 
                
                ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));    
                StringBody comment = new StringBody("123哈哈哈45", contentType);
                MultipartEntityBuilder builder=MultipartEntityBuilder.create();
                
                builder.setCharset(Charset.forName("UTF-8"));//设置请求的编码格式  
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式 
                
                //文件流参数
                builder.addPart("bin",bin);
                builder.addPart("bi哈哈n2",bin2);
                //普通的参数
                builder.addPart("employee_no",comment);
                HttpEntity reqEntity= builder.build();
                httppost.setEntity(reqEntity);  
                System.out.println("executing request " + httppost.getRequestLine());  
                CloseableHttpResponse response = httpclient.execute(httppost);  
                try {  
                    System.out.println(response.getStatusLine());  
                    HttpEntity resEntity = response.getEntity();  
                    if (resEntity != null) {  
                        System.out.println("Response content length: " + resEntity.getContentLength());  
                        System.out.println("Response content: " + EntityUtils.toString(resEntity,"UTF-8"));  
                    }  
                } finally {  
                    response.close();  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            } finally {  
                try {  
                    httpclient.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  

    2、后台下载代码,原生servlet

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            PrintWriter out = null;  
            //跨越访问
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");         
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");  
    
            FileItemFactory factory = new DiskFileItemFactory();  
            ServletFileUpload upload = new ServletFileUpload(factory);  
            File directory = null;    
            List<FileItem> items = new ArrayList<FileItem>();  
            try {  
                items = upload.parseRequest(request);  
                // 得到所有的文件  
                Iterator<FileItem> it = items.iterator();  
                while (it.hasNext()) {  
                    FileItem fItem = (FileItem) it.next();  
    
                    if (fItem.isFormField()) {  
                        // 普通文本框的值 
                        System.out.println(fItem.getFieldName()+fItem.getString("UTF-8"));
                    } else { // 获取上传文件的值  
                        String name = fItem.getName();  
                        if(name != null && !("".equals(name))) {  
                            name = name.substring(name.lastIndexOf(File.separator) + 1);  
                            directory = new File("d://test");    
                            directory.mkdirs();  
                            String filePath = ("d://test")+ File.separator + name;  
                            InputStream is = fItem.getInputStream();  
                            FileOutputStream fos = new FileOutputStream(filePath);  
                            byte[] buffer = new byte[1024];  
                            while (is.read(buffer) > 0) {  
                                fos.write(buffer, 0, buffer.length);  
                            }  
                            fos.flush();  
                            fos.close();  
                        }  
                    }  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            try {  
                out = response.getWriter();  
                out.print("{success:true, msg:'接收成功'}");  
                out.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }

    3、后台下载代码,SpringMVC

    public List<String> UploadImage(HttpServletRequest request) {
    
            List<String> list=new ArrayList<>();
            String employee_no=request.getParameter("employee_no");
            String tmppath=File.separator+"img"+File.separator +employee_no+File.separator;
            String BasePath=request.getRealPath("/")+tmppath;
            String BaseUrl=request.getLocalAddr()+":"+request.getLocalPort()+tmppath;
            System.out.println(BaseUrl);
            try {
                File directory=new File(BasePath);
                if(!directory.exists()){
                    directory.mkdirs(); 
                }
                //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)
                CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
                //检查form中是否有enctype="multipart/form-data"
                if(multipartResolver.isMultipart(request))
                {
                    //将request变成多部分request
                    MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
                    //获取multiRequest 中所有的文件名
                    Iterator iter=multiRequest.getFileNames();
                    while(iter.hasNext())
                    {
                        //一次遍历所有文件
                        MultipartFile file=multiRequest.getFile(iter.next().toString());
                        if(file!=null)
                        {
                            String name=file.getOriginalFilename();
                            System.out.println(file.getName()+name);
                            String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
                            String ext=name.substring(name.lastIndexOf("."),name.length());
                            String filePath = BasePath+uuid+ext;
                            file.transferTo(new File(filePath));
                            list.add(BaseUrl+uuid+ext);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return list;
        }
  • 相关阅读:
    Effective C# 原则37:使用标准的配置机制(译)
    Effective C# 原则31:选择小而简单的函数(译)
    Effective C# 原则24:选择申明式编程而不是命令式编程(译)
    Effective C# 原则34:创建大容量的Web API(译)
    Effective C# 原则27:避免使用ICloneable(译)
    Effective C# 第4章:创建基于二进制的组件(译)
    Effective C# 原则39:使用.Net验证(译)
    Effective C# 原则35:选择重写函数而不是使用事件句柄(译)
    Effective C# 原则25: 让你的类型支持序列化(译)
    Effective C# 原则38:使用和支持数据绑定(译)
  • 原文地址:https://www.cnblogs.com/zhangjinru123/p/7521286.html
Copyright © 2011-2022 走看看