zoukankan      html  css  js  c++  java
  • 下载文件时设置文件名的方法

    在阿里云云存储OSS中下载文件时设置文件名的办法:

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import com.aliyun.openservices.oss.OSSClient;
    import com.aliyun.openservices.oss.model.GeneratePresignedUrlRequest;
    import com.aliyun.openservices.oss.model.ObjectMetadata;
    import com.aliyun.openservices.oss.model.PutObjectResult;
    import com.aliyun.openservices.oss.model.ResponseHeaderOverrides;
    
    public class Sample {
    
        public static void main(String[] args) throws IOException, ParseException {
            //http://aliyun_portal_storage.oss.aliyuncs.com/oss_api/oss_javahtml/index.html
            //OSS的用户名与密码
            String accessKeyId = "w5c4HJfSXoegx74M";
            String accessKeySecret = "**************";        
            String endpoint = "http://oss-cn-qingdao.aliyuncs.com";
            OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //http://bbs.aliyun.com/read/149100.html     
            String bucketName="resource-ds";
            
            //判断一下Bucket是不是存在
            /*
            if(!client.doesBucketExist(bucketName))
            {
                // 新建一个Bucket
                //由于Bucket的名字是全局唯一的,所以尽量保证你的 bucketName 不与别人重复。
                client.createBucket(bucketName);   
                client.setBucketAcl(bucketName, CannedAccessControlList.Private);
                System.out.println("创建Bucket成功完成!");            
            }
            */
            //删除Bucket
            //client.deleteBucket(bucketName);
            //System.out.println("删除Bucket成功完成!");
            
            //上传一个文件
            String filePath="F:\Download\20140418120446935.png";
            // 获取指定文件的输入流
            File file = new File(filePath);
            InputStream content = new FileInputStream(file);
    
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
    
            // 必须设置ContentLength
            meta.setContentLength(file.length());
            String key="test/"+new File(filePath).getName();
            // 上传Object.
            PutObjectResult result = client.putObject(bucketName, key, content, meta);
    
            // 打印ETag
            System.out.println("上传文件的MD5值"+result.getETag());
            
            //显示中文名称的
            //Date expires = new Date (new Date().getTime() + 1000000000 * 60*60); // 10 minute to expire
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date expires = format.parse("2080-01-01 00:00:00");
            GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
            generatePresignedUrlRequest.setExpiration(expires);
            
            ResponseHeaderOverrides responseHeaders=new ResponseHeaderOverrides();
            //不同浏览器上中文文件名的下载乱码问题
            //http://java-xp.iteye.com/blog/903048
            String filename="黄海测试.png";
            
            //For IE
            String new_filename = URLEncoder.encode(filename, "UTF8");  
            responseHeaders.setContentDisposition("attachment;filename="+new_filename);
            generatePresignedUrlRequest.setResponseHeaders(responseHeaders);
            URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
            System.out.println(url.toString().Replace("+","%2B"));
            
            //For FireFox And Chrome
            new_filename = filename;  
            responseHeaders.setContentDisposition("attachment;filename="+new_filename);
            generatePresignedUrlRequest.setResponseHeaders(responseHeaders);
            url = client.generatePresignedUrl(generatePresignedUrlRequest);
            System.out.println(url.toString().Replace("+","%2B"));                
            
            /*
            // 获取指定bucket下的所有Object信息
            ObjectListing listing = client.listObjects(bucketName);
    
            // 遍历所有Object
            for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                System.out.println(objectSummary.getKey());
            }
            
            //下载
            OSSObject mydown=client.getObject(bucketName, key);
            InputStream  is   =mydown.getObjectContent();
         
            // 1K的数据缓冲  
            byte[] bs = new byte[1024];  
            // 读取到的数据长度  
            int len;  
            // 输出的文件流  
           String savePath="c:\1.doc";
             
           OutputStream os = new FileOutputStream(savePath);  
            // 开始读取  
            while ((len =  is .read(bs)) != -1) {  
              os.write(bs, 0, len);  
            }  
            // 完毕,关闭所有链接  
            os.close();  
            is .close();  
            */
        }
    }

     

    在nginx中配置中文文件名称,在各种浏览器和迅雷中都能正确下载中文文件名的办法:

    
    


    #user nobody;
    worker_processes 4;
    worker_rlimit_nofile 100000;

    
    

    #error_log logs/error.log;
    #error_log logs/error.log notice;
    #error_log logs/error.log info;

    
    

    #pid logs/nginx.pid;

    
    


    events {
    use epoll;
    multi_accept on;
    worker_connections 2048;
    }

    
    


    http {
    include mime.types;
    default_type application/octet-stream;

    
    

    #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
    # '$status $body_bytes_sent "$http_referer" '
    # '"$http_user_agent" "$http_x_forwarded_for"';

    
    

    #access_log logs/access.log main;

    
    

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    client_header_buffer_size 128k;
    client_body_buffer_size 512k;
    large_client_header_buffers 4 128k;

    
    

    #keepalive_timeout 0;
    keepalive_timeout 65;

    
    

    gzip on;
    gzip_min_length 1k;
    gzip_buffers 16 64k;
    gzip_http_version 1.1;
    gzip_comp_level 6;
    gzip_types text/plain application/x-javascript text/css application/xml;
    gzip_vary on;

    
    

    upstream backend {
    server 127.0.0.1:8080;
    }

    
    

    #加载lua的初始化文件
    init_by_lua_file /usr/local/lua_script/init.lua;

    
    

    server {
    listen 80;
    server_name localhost;

    
    

    charset utf-8;

    
    

    #access_log logs/host.access.log main;

    
    

    location / {
    #root html;
    #index index.html index.htm;
    root /usr/local/tomcat7/webapps/;
    proxy_pass http://backend;
    }

    location /down/ {
    if ($arg_flag = "download")
    {
    #参考:http://ju.outofmemory.cn/entry/71360

    
    

    add_header Content-Encoding "utf-8";
    add_header Content-Type "x-msdownload";

    add_header Cache-Control "private";
    add_header Accept-Rangles "bytes";

    
    

    add_header Content-Disposition "attachment;filename=$arg_n;filename*=UTF-8''$arg_n;";
    add_header Pragma "no-cache";
    add_header Expires "0";
    }
    alias /usr/local/openresty/nginx/html/down/;
    }

    
    

    #配置Nginx动静分离,定义的静态页面直接从Nginx发布目录读取。
    location ~* ^/(?![down]).(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)
    {
    root /usr/local/tomcat7/webapps;
    #expires定义用户浏览器缓存的时间为3天,如果静态页面不常更新,可以设置更长,这样可以节省带宽和缓解服务器的压力
    expires 3d;
    }

    
    

    location /dsideal_yy/login/doLogin {
    content_by_lua_file /usr/local/lua_script/login.lua;
    }

    
    

    location /dsideal_yy/resource/getStageSubject {
    content_by_lua_file /usr/local/lua_script/xd_subject.lua;
    }

    
    

    location /dsideal_yy/resource/getAllScheme {
    content_by_lua_file /usr/local/lua_script/version.lua;
    }

    
    

    location /dsideal_yy/resource/getResourceList {
    content_by_lua_file /usr/local/lua_script/resource_list.lua;
    }

    
    

    location /dsideal_yy/resource/getResourceMyList {
    content_by_lua_file /usr/local/lua_script/resource_my_list.lua;
    }

    location /utf_code {
    content_by_lua_file /usr/local/lua_script/utf_code.lua;
    }

    
    

    location /dsideal_yy/resource/setDownCount {
    content_by_lua_file /usr/local/lua_script/down_count.lua;
    }

    
    

    location /dsideal_yy/resource/getStructureInfo {
    content_by_lua_file /usr/local/lua_script/structure.lua;
    }

    
    

    location /dsideal_yy/resource/getPersonXdkm {
    content_by_lua_file /usr/local/lua_script/person_xdkm_get.lua;
    }

    
    

    location /dsideal_yy/resource/savePerosnXdkm {
    content_by_lua_file /usr/local/lua_script/person_xdkm_set.lua;
    }

    
    

    location /dsideal_yy/resource/getMediaTypeByXdkm {
    content_by_lua_file /usr/local/lua_script/media_type.lua;
    }

    
    

    #error_page 404 /404.html;

    
    

    # redirect server error pages to the static page /50x.html
    #
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    root html;
    }

    
    

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ .php$ {
    # proxy_pass http://127.0.0.1;
    #}

    
    

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ .php$ {
    # root html;
    # fastcgi_pass 127.0.0.1:9000;
    # fastcgi_index index.php;
    # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
    # include fastcgi_params;
    #}

    
    

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /.ht {
    # deny all;
    #}
    }

    
    


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    # listen 8000;
    # listen somename:8080;
    # server_name somename alias another.alias;

    
    

    # location / {
    # root html;
    # index index.html index.htm;
    # }
    #}

    
    


    # HTTPS server
    #
    #server {
    # listen 443 ssl;
    # server_name localhost;

    
    

    # ssl_certificate cert.pem;
    # ssl_certificate_key cert.key;

    
    

    # ssl_session_cache shared:SSL:1m;
    # ssl_session_timeout 5m;

    
    

    # ssl_ciphers HIGH:!aNULL:!MD5;
    # ssl_prefer_server_ciphers on;

    
    

    # location / {
    # root html;
    # index index.html index.htm;
    # }
    #}

    
    

    }

     
  • 相关阅读:
    Jmeter中的变量(三)
    Jmeter组件和属性(二)
    Jmeter配置元件执行顺序
    Fiddler Web Session 列表(1)
    selenium webdriver操作各浏览器
    java1.8环境配置+win10系统
    python函数库及函数标准库
    MySql 数据库基础命令
    Linux 常用命令
    normalize.css
  • 原文地址:https://www.cnblogs.com/littlehb/p/3727973.html
Copyright © 2011-2022 走看看