腾讯云上传文件,下载文件方法注释

1447 篇文章 12 订阅
1447 篇文章 7 订阅

$appid = 'id';
        $bucket = '桶名';
        $SecretId = 'id';
        $SecretKey = 'key';
        $path = '文件路径可自定义';
        $region = '桶所在服务器缩写:ap-beijing';
        $cosClient = new \Qcloud\Cos\Client(
            array('region' => $region,
                    'credentials' => array(
                        'appId' => $appid,
                        'secretId' => $SecretId,
                        'secretKey' => $SecretKey
                    )
                )
            );
        //获取bucket列表
        //$result = $cosClient->listBuckets();
        //print_r($result);
        //return view( $this->_skin .'.index',compact('infos','infos_seo'));
        //上传文件
        // try {
        //     $result = $cosClient->upload(
        //         //bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
        //         $bucket= $bucket,
        //         //$key = '444.txt',//上传的文件名,可以不存在,下面的Body会给此文件写入内容
        //         //$body = '改变内容上传',//把变量内容写入到上面的$key文件中去并上传
        //         $key = '5.txt',//上传的文件名,可以不存在,下面的Body会给此文件写入内容
        //         $body = fopen('./hello.txt', 'rb'),//打开指定的文件把内容写入到上面的$key文件中去并上传
        //         $options = array(
        //             "ACL"=>'private',
        //             'CacheControl' => 'private'));
        //     print_r($result);
        // } catch (\Exception $e) {
        //     echo "$e\n";
        // }
        // 下载文件到本地
        $result = $cosClient->getObject(array(
            //bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
            'Bucket' => $bucket,
            'Key' => '5.txt',//服务器下载的文件
            'SaveAs' => './444.txt'));//下载之后的文件路径及新命名
            echo($result);

    }

//另外上传方式,使用form表单上传

$appid = config( 'file.tengxun_cos.appid');

$bucket = config( 'file.tengxun_cos.bucket');

$SecretId = config( 'file.tengxun_cos.SecretId');

$SecretKey = config( 'file.tengxun_cos.SecretKey');

if ( $request-> hasFile( 'file')) {

$image = $request-> file( 'file');

print_r( $image);

$cosClient = new \Qcloud\Cos\ Client(

array(

'region' => 'ap-beijing',

'credentials' => array(

'appId' => $appid,

'secretId' => $SecretId,

'secretKey' => $SecretKey

)

)

);

// $result_upload = $cosClient->upload(

// $bucket = $bucket,

// $key = time() . '_' . rand(1000000, 9999999) . '.' . $image->getClientOriginalExtension(),

// $body = $image->getRealPath()

$options = array(

"ACL" => 'private',

'CacheControl' => 'private'

)

// );

$result_upload = $cosClient-> putObject(

array(

'Bucket' => $bucket,

'Key' => time() . '_' . rand( 1000000, 9999999) . '.' . $image-> getClientOriginalExtension(),

//'Body' => $image

'Body' => file_get_contents( $image-> getRealPath())//此处非常重要,需要获得文件路径,使用文件流上传

)

// $options = array(

// "ACL" => 'private',

// 'CacheControl' => 'private'

// )

);

// $result_upload = object_to_array($result_upload);

print_r( $result_upload);

exit;

} else {

$response = array(

'status' => 500,

'message' => '请选择要上传的文件'

);

}

return $response;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
文件上传代码及注释如下: ```java import java.io.File; import java.io.IOException; import java.util.UUID; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class FileController { @Value("${file.upload.path}") private String uploadPath; // 上传文件的路径,从配置文件中读取 @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { // 判断上传的文件是否为空 return "redirect:/error"; } // 生成一个唯一的文件名 String fileName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename(); File destFile = new File(uploadPath + "/" + fileName); try { file.transferTo(destFile); // 将文件保存到磁盘中 return "redirect:/success"; } catch (IOException e) { e.printStackTrace(); return "redirect:/error"; } } } ``` 文件上传的主要逻辑是通过 `MultipartFile` 类型的参数来接收上传的文件,然后将其保存到指定的路径中。 文件下载代码及注释如下: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @Controller public class FileController { @Value("${file.upload.path}") private String uploadPath; // 上传文件的路径,从配置文件中读取 @GetMapping("/download/{fileName:.+}") public void downloadFile(@PathVariable("fileName") String fileName, HttpServletResponse response) { File file = new File(uploadPath + "/" + fileName); if (!file.exists()) { // 判断文件是否存在 return; } try (FileInputStream inputStream = new FileInputStream(file); OutputStream outputStream = response.getOutputStream()) { response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); byte[] buffer = new byte[4096]; int length; while ((length = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } } ``` 文件下载的主要逻辑是通过 `HttpServletResponse` 类型的参数来向客户端输出文件。在输出文件之前,需要设置响应头,包括内容类型和文件名。然后读取文件内容并写入输出流中即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值