springboot项目上传文件处理

一、后端使用spring-web-5.2.3.RELEASE.jar的MultipartHttpServletRequest类处理文件上传


import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class filetest {

    //本地文件目录
    private static String tmpPath = "D:\\file";

    //阿里云文件目录
    private static String alPath = "picture/";

    @RequestMapping("/upload_original_pic")
    @ResponseBody
    public Map<String, Object> perFileUpload(HttpServletRequest request) {

        String fileFieldStorageFileName = "";
        File file = null;
        Map<String, Object> response = new HashMap<>();
        try {
            //接收前端传的文件
            MultipartFile requestFile = ((MultipartHttpServletRequest) request).getFile("file");
            if (requestFile == null) {
                response.put("errorMessage", "文件为空");
                return response;
            }

            // 创建文件存放路径实例
            File dest = new File(tmpPath);

            // 判断文件夹不存在就创建
            if (!dest.exists()) {
                dest.mkdirs();
            }

            String fileName = requestFile.getOriginalFilename();//文件名
            String contentType = requestFile.getContentType();//文件类型
            
            //获取文件扩展名
			String fileExtension = com.google.common.io.Files.getFileExtension(fileName);

            //生成上传到阿里云的文件名(避免因重复而覆盖)
            String alfielName = DateUtils.getDateString(new Date(), "yyyyMMddHHmmss") + RandomStringUtils.random(8, true, false);
            
            //在本地创建一个临时文件
            file = new File(tmpPath + "/" + alfielName + "." + fileExtension);
            
            //生成本地文件的动作
            requestFile.transferTo(file);

            //阿里云上的目录+文件名
            String formatName = alPath + "/" + file.getName();

            fileFieldStorageFileName  = putObject(formatName, file.getAbsolutePath(), contentType); 
        } catch (Exception e) {
            response.put("errorMessage", "上传图片失败!" + e.getMessage());
            return response;
        } finally {
            //删除本地文件
            if (file != null) {
                file.delete();
            }
        }
        //上传到阿里云的路径
        response.put("filePath", "上传图片成功路径为:"+fileFieldStorageFileName);
        return response;

    }

    //阿里云OSSbucket地址
    private static String SSO_BUCKET = "hao91-test";

    //阿里云OSS域配置
    private static String ALIYUN_END_POINT = "http://oss-cn-qingdao.aliyuncs.com/";

    /*
    上传到阿里云服务的位置为 ALIYUN_END_POINT 和 SSO_BUCKET的组合
    http://hao91-test.oss-cn-qingdao.aliyuncs.com
    */

    //阿里云accessKeyId
    private static String accessKeyId = "LTxxxxxxxx006hNp";

    //阿里云accessKeySecret
    private static String accessKeySecret = "YPsOWxxxxxxxxxxxxxxxqct2LQtMrl";

    public String putObject(String formatName, String filePath, String contentType) throws FileNotFoundException {
        OSSClient client = new OSSClient(ALIYUN_END_POINT, accessKeyId, accessKeySecret);
        File file = new File(filePath);
        InputStream content = new FileInputStream(file);
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.length());
        meta.setContentType(contentType);
        meta.setLastModified(new Date());
        PutObjectResult result = client.putObject(SSO_BUCKET, formatName, content, meta);

        try {
            content.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] split = ALIYUN_END_POINT.split("//");

        String pasth = split[0] + "//" + SSO_BUCKET + "." + split[1] + formatName;
        //              https:  //    hao91-test . oss-cn-qingdao.aliyuncs.com/  + formatName;
        System.out.println("上传到阿里云的地址为:"+pasth);
        
        return pasth ;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值