将文件上传到阿里云oss中

将文件上传到阿里云oss中Controller层

package com.shopx5.controller.shop;

import java.io.*;
import java.net.URL;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.shopx5.common.shop.Result;

/**
 * @author tang ShopX5多商户商城系统
 * @qq 1503501970
 */
@RestController
@RequestMapping("/shopx5/upload")
public class UploadController {


    @RequestMapping("/uploadFile")
    public Result uploadFile(MultipartFile file, HttpServletRequest request) {
        try {

            String url = ossUpload(file);


            return new Result(true, url);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "上传失败!");
        }
    }

    public String ossUpload(MultipartFile uploadFile) throws IOException {
        //文件名
        String fileName = uploadFile.getOriginalFilename();

        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        // 生成上传文件名
        String newFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;

        //生成存储路径
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String objectName = sdf.format(new Date()) + "/" + newFileName;

        //生成新的文件
        InputStream ins = uploadFile.getInputStream();
        File file=new File(uploadFile.getOriginalFilename());
        inputStreamToFile(ins, file);
		
		//根据情况填写
        String endpoint = "";
        String accessKeyId = "";
        String accessKeySecret = "";
        String bucketName = "";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        ossClient.putObject(bucketName, objectName, file);
        // 设置URL过期时间为10年。
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000 * 24 * 365 * 10);
        // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        ossClient.shutdown();
        
        return url.toString();
    }

    public void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

package com.shopx5.common.shop;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 用于向页面传递信息的类
 * @author tan g S h op X 5 多商户商城
 * @qq 15 035 019 70
 */
public class Result implements Serializable{
	private boolean success;
	private boolean flag;
	private String message;
	private List list;
	private Map<String,Object> data;

	public Result(boolean success, String message) {
		super();
		this.success=success;
		this.flag = success;
		this.message = message;
	}
	public Result(boolean success, List list) {
		super();
		this.success=success;
		this.flag = success;
		this.list = list;
	}
	public Result() {
		super();
	}
	public boolean isFlag() {
		return flag;
	}
	public void setFlag(boolean flag) {
		this.flag = flag;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	
	public boolean isSuccess() {
		return success;
	}
	public void setSuccess(boolean success) {
		this.success = success;
	}
	public List getList() {
		return list;
	}
	public void setList(List list) {
		this.list = list;
	}

	public Map<String, Object> getData() {
		return data;
	}

	public void setData(Map<String, Object> data) {
		this.data = data;
	}
}

页面代码

 <form enctype="multipart/form-data" id="" method="post">
                                    <tr>
                                        <td>
                                            <table>
                                                <tr>
                                                    <td><input type="file" id="file"/><br>
                                                        <button class="btn btn-primary" type="button"
                                                                onclick="uploadFile()">上传
                                                        </button>
                                                    </td>
                                                    <td><img id="img1" style="display: none;width: 150px;height: 100px"
                                                             src="#">
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                </form>
                            </div>
                        </div>

JS:使用ajax

 <script type="text/javascript">
            function uploadFile() {
                var formData = new FormData();
                // 向formData中添加数据:
                formData.append("file", file.files[0]); //file是文件上传框: 取第一个file框<input type="file" id="file" />
                $.ajax({
                    url: "/shopx5/upload/uploadFile",
                    type: "post",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        if (true == res.success) {
                            $("#img1").attr("src", res.message);
                            $("#img1").show();
                            $("#idCardUrl1").val(res.message);
                        }
                    },
                    error: function (err) {
                        alert("网络连接失败,稍后重试", err);
                    }
                })
            }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值