springboot上传图片视频到文件服务器

项目pom.xml中引入jar包
	<dependency>
	      <groupId>com.sun.jersey</groupId>
	       <artifactId>jersey-client</artifactId>
	       <version>1.19.4</version>
    </dependency>
    <dependency>
          <groupId>org.glassfish.jersey.core</groupId>
          <artifactId>jersey-client</artifactId>
          <version>2.27</version>
      </dependency>
创建帮助类 FileUploadUtil
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.io.FileUtils;

public class FileUploadUtil {
	 /**
     * 取出文件后缀名
     *
     * @param fileName
     * @return
     */
    public static String getFileSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    public static String newFileName(String suffix) {
        String prefix = StringUtils.getUniqueNo();
        return prefix + suffix;
    }

    /**
     * 文件复制
     * @param srcPath 源文件路径
     * @param targetPath 复制后存放路径
     * @throws Exception
     */
    public static void copyFile(String srcPath, String targetPath) throws Exception {
        File srcFile = new File(srcPath);
        File target = new File(targetPath);
        if (!srcFile.exists()) {
            throw new Exception("文件不存在!");
        }
        if (!srcFile.isFile()) {
            throw new Exception("不是文件!");
        }
        //判断目标路径是否是目录
        if (!target.isDirectory()) {
            throw new Exception("文件路径不存在!");
        }

        // 获取源文件的文件名
        String fileName = srcPath.substring(srcPath.lastIndexOf("/") + 1);
        //TODO:判断是否存在相同的文件名的文件
        File[] listFiles = target.listFiles();
        for (File file : listFiles) {
            if(fileName.equals(file.getName())){
                fileName += "_1";
            }
        }
        String newFileName = targetPath + File.separator + fileName;
        File targetFile = new File(newFileName);
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(targetFile);
            //从in中批量读取字节,放入到buf这个字节数组中,
            // 从第0个位置开始放,最多放buf.length个 返回的是读到的字节的个数
            byte[] buf = new byte[8 * 1024];
            int len = 0;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try{
                if(in != null){
                    in.close();
                }
            }catch(Exception e){
                System.out.println("关闭输入流错误!");
            }
            try{
                if(out != null){
                    out.close();
                }
            }catch(Exception e){
                System.out.println("关闭输出流错误!");
            }
        }
    }

    /**
     * title        :  获取文件md5值
     * @Author      :  lyp
     * @Date        :  16:21 2019/10/16
     * @Param       :
     * @return      :
    **/
    public static String getMD5Ssum(String path) {
        StringBuffer sb = new StringBuffer("");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(FileUtils.readFileToByteArray(new File(path)));
            byte b[] = md.digest();
            int d;
            for (int i = 0; i < b.length; i++) {
                d = b[i];
                if (d < 0) {
                    d = b[i] & 0xff;
                    // 与上一行效果等同
                    // i += 256;
                }
                if (d < 16)
                    sb.append("0");
                sb.append(Integer.toHexString(d));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}
Controller层
    
    /**
     * 接收上传的文件,并且将上传的文件存储在指定路径下
     * @param request
     * @return
     * @throws IOException 
     */
    @SuppressWarnings("deprecation")
	@RequestMapping(value = "/upload")
    public String upload(@RequestParam("file")MultipartFile file) throws IOException {
        byte[] imageData = file.getBytes();
        //文件后缀
        String suffix = FileUploadUtil.getFileSuffix(file.getOriginalFilename());
        String fileName = FileUploadUtil.newFileName(suffix);
        System.out.println( saveImage(fileName,imageData,"/imgs/"));
		return null;
    }
    
    
    
    public static String saveImage(String fileName, byte[] fileData, String relativePath) {
        relativePath = relativePath == null ? "" : relativePath;
        String filePath = relativePath + fileName;
        return upload(filePath, fileData);
    }
    
    /**
     * 上传文件到服务器 重复文件不再上传
     *
     * @param filePath 如 /test.jpg
     * @param fileData 文件数据
     * @return filePath
     */
    private static String upload(String filePath, byte[] fileData) {
     
        String url =FAR_SERVICE_DIR+ filePath;
        
        Client client = new Client();
        WebResource resource = client.resource(url);
        resource.put(String.class, fileData);
        return filePath;
    }
 //指定一个临时路径作为上传目录
private static final String FAR_SERVICE_DIR = "http://xx.xx.xx/upload";//远程服务器接受文件的路由

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值