美文网首页
Http的上传(下载)图片

Http的上传(下载)图片

作者: 君袅 | 来源:发表于2019-02-21 16:28 被阅读0次

    上传

    建立一个工具类

    public class UploadFile {
        // 分割符,自己定义即可
        private static final String BOUNDARY = "----WebKitFo";
        private static final String TAG = "UploadFile";
    
        /**
         * 上传文件 到服务器
         *
         * @param params       post参数
         * @param fileFormName 文件在表单中的键 key=img  file =文件流
         * @param uploadFile   上传的文件
         * @param urlStr       上传服务器地址url
         * @throws Exception
         */
        public static void uploadFile(Map<String, String> params, String fileFormName, File uploadFile, String urlStr) throws Exception {
    
            String newFileName = uploadFile.getAbsolutePath().substring(uploadFile.getAbsolutePath().lastIndexOf("/") + 1);
            if (newFileName == null || newFileName.trim().equals("")) {
                newFileName = uploadFile.getName();
            }
            StringBuilder stringBuilder = new StringBuilder();
            if (params != null) {
                for (String key : params.keySet()) {
                    stringBuilder.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n");
                    stringBuilder.append("\r\n");
                    stringBuilder.append(params.get(key) + "\r\n");
                }
            }
    
            stringBuilder.append("--" + BOUNDARY + "\r\n");
            stringBuilder.append("Content-Disposition: form-data; name=\"" + fileFormName + "\"; filename=\"" + newFileName + "\""
                    + "\r\n");
            stringBuilder.append("Content-Type: image/jpg" + "\r\n");// 如果服务器端有文件类型的校验,必须明确指定ContentType
            stringBuilder.append("\r\n");
            byte[] headerInfo = stringBuilder.toString().getBytes("UTF-8");
            byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
    
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(10*1000);
            conn.setRequestProperty("Connection", "close");
            // 设置传输内容的格式,以及长度
            conn.setRequestProperty("Content-Type", "image/jpg; boundary=" + BOUNDARY);
            conn.setRequestProperty("Content-Length", (headerInfo.length + uploadFile.length() + endInfo.length) + "");
            conn.setDoOutput(true);
            OutputStream out = conn.getOutputStream();
    
            InputStream in = new FileInputStream(uploadFile);
            //写入的文件长度
            int count = 0;
            //文件的总长度
            int available = in.available();
            // 写入头部 (包含了普通的参数,以及文件的标示等)
            out.write(headerInfo);
            // 写入文件
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
                count += len;
                int progress = count * 100 / available;
                Log.d(TAG, "上传进度: " + progress + " %");
    //            updateProgress(progress);
            }
            // 写入尾部
            out.write(endInfo);
            in.close();
            out.close();
            if (conn.getResponseCode() == 200) {
                System.out.println("文件上传成功");
                String result = stream2String(conn.getInputStream());
                Log.d(TAG, "uploadForm: " + result);
            }
    
        }
    
        public static String stream2String(InputStream is) {
            int len;
            byte[] bytes = new byte[1024];
            StringBuffer sb = new StringBuffer();
            try {
                while ((len = is.read(bytes)) != -1) {
                    sb.append(new String(bytes, 0, len));
                }
                is.close();
                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "";
        }
    }
    

    使用

        private static final String TAG = "MainActivity";
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                default:
                    break;
                case R.id.click:
    
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            uploadFile();
                        }
                    }.start();
    
                    break;
            }
        }
    
    
        private void uploadFile() {
            String filePath = Environment.getExternalStorageDirectory() + File.separator + "aa.jpg";
            File file = new File(filePath);
            if (file.exists()) {
                Log.d(TAG, "exists: " + true);
            }
    
    
            String url = "http://yun918.cn/study/public/file_upload.php";
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("key", "img");
            try {//String fileFormName, File uploadFile,  String urlStr
                UploadFile.uploadFile(hashMap, file.getName(), file, url);
    
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    ···
    
    #下载
    

    public class Main3Activity extends AppCompatActivity implements View.OnClickListener {

    /**
     * 下载
     */
    private Button mClick;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        initView();
    
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }
    }
    private static final String TAG = "MainActivity";
    private final String DEFAULT_TARGET_FOLDER_PATH = Environment.getExternalStorageDirectory() + File.separator;
    
    private void doHttpTask(String  fileUrl) {
        try {
    

    // /sdcar/0/xx.png
    String name = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
    File file = new File(DEFAULT_TARGET_FOLDER_PATH+name);
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    HttpURLConnection connection = getConnection(fileUrl);
    InputStream inputStream = connection.getInputStream();

            byte[] bytes = new byte[8*1024];
            int hasRead;
            while ((hasRead = inputStream.read(bytes)) > 0) {
                fileOutputStream.write(bytes, 0, hasRead);
    
                Log.d(TAG, "doHttpTask: 当次写入=--"+hasRead);
            }
                fileOutputStream.close();
                inputStream.close();
                connection.disconnect();
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
        }
    }
    
    public static HttpURLConnection getConnection(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10*1000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
        conn.setRequestProperty("Connection", "Keep-Alive");
    

    // conn.setRequestProperty("Accept-Encoding", "identity");
    return conn;
    }
    private void initView() {
    mClick = (Button) findViewById(R.id.click);
    mClick.setOnClickListener(this);
    }
    private String apk_url = "https://ws1.sinaimg.cn/large/0065oQSqgy1fze94uew3jj30qo10cdka.jpg";

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.click:
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        doHttpTask("https://ws1.sinaimg.cn/large/0065oQSqgy1fze94uew3jj30qo10cdka.jpg");
                    }
                }.start();
                break;
        }
    }
    

    }

    
    

    相关文章

      网友评论

          本文标题:Http的上传(下载)图片

          本文链接:https://www.haomeiwen.com/subject/ciqdyqtx.html