使用(七牛云)为例子实现将文件上传到云服务器

目的

目前,用户的头像、分享生成的长图等文件都是存放在本地的,我们可以将他们存放在云服务器中,此处我们使用七牛云作为例子示范。

七牛云

创建账户并申请如下的两个bucket,分别是用户头像的存储空间和分享长图的存储空间。
在这里插入图片描述

导入依赖

		<!-- https://mvnrepository.com/artifact/com.qiniu/qiniu-java-sdk -->
		<dependency>
			<groupId>com.qiniu</groupId>
			<artifactId>qiniu-java-sdk</artifactId>
			<version>7.13.1</version>
		</dependency>

配置

# qiniu
qiniu.key.accessKey=
qiniu.key.secretKey=
qiniu.bucket.header.name=coderforum-header
qiniu.bucket.header.url=
qiniu.bucket.share.name=coderforum-share
qiniu.bucket.share.url=

Controller

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${qiniu.key.accessKey}")
    private String accessKey;

    @Value("${qiniu.key.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket.header.name}")
    private String headerBucketName;

    @Value("${qiniu.bucket.header.url}")
    private String headerBucketUrl;

    @LoginRequired
    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    public String getSettingPage(Model model) {
        // set the name of the uploaded file
        String fileName = CommunityUtil.generateUUID();

        // set the information of the response
        StringMap policy = new StringMap();
        policy.put("returnBody", CommunityUtil.getJSONString(0));

        // generate the certificate of uploading
        Auth auth = Auth.create(accessKey, secretKey);
        String uploadToken = auth.uploadToken(headerBucketName, fileName, 3600, policy);

        model.addAttribute("uploadToken", uploadToken);
        model.addAttribute("fileName", fileName);

        return "/site/setting";
    }

    // update the path of profile picture
    @PostMapping(path = "/header/url")
    @ResponseBody
    public String updateHeaderUrl(String fileName){
        if(StringUtils.isBlank(fileName)){
            return CommunityUtil.getJSONString(1, "The file name cane is required.");
        }

        String url = headerBucketUrl + "/" + fileName;
        userService.updateHeader(hostHolder.getUser().getId(), url);

        return CommunityUtil.getJSONString(0);
    }
}

前端

<!--				上传到云服务器(七牛云)-->
				<form class="mt-5" id="uploadForm">
					<div class="form-group row mt-4">
						<label for="head-image" class="col-sm-2 col-form-label text-right">choose a photo:</label>
						<div class="col-sm-10">
							<div class="custom-file">
								<input type="hidden" name="token" th:value="${uploadToken}">
								<input type="hidden" name="key" th:value="${fileName}">
								<input type="file" class="custom-file-input" id="head-image" name="file" lang="es" required="">
								<label class="custom-file-label" for="head-image" data-browse="文件">select a photo</label>
								<div class="invalid-feedback">
									This account does not exist!
								</div>
							</div>
						</div>
					</div>
					<div class="form-group row mt-4">
						<div class="col-sm-2"></div>
						<div class="col-sm-10 text-center">
							<button type="submit" class="btn btn-info text-white form-control">upload</button>
						</div>
					</div>
				</form>


	<script th:src="@{/js/setting.js}"></script>

相应的js文件:

$(function(){
    $("#uploadForm").submit(upload);
});

function upload() {
    $.ajax({
        url: "https://upload-z1.qiniup.com",
        method: "post",
        processData: false,
        contentType: false,
        data: new FormData($("#uploadForm")[0]),
        success: function(data) {
            if(data && data.code == 0) {
                // 更新头像访问路径
                $.post(
                    CONTEXT_PATH + "/user/header/url",
                    {"fileName":$("input[name='key']").val()},
                    function(data) {
                        data = $.parseJSON(data);
                        if(data.code == 0) {
                            window.location.reload();
                        } else {
                            alert(data.msg);
                        }
                    }
                );
            } else {
                alert("Upload failed!");
            }
        }
    });
    return false;
}

查看

文件已经存入七牛云
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值