附件上传下载

   /*
     * @Description //附件上传
     * @Param [file]
     * @return org.gocom.coframe.sdk.model.common.Response
     **/
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public Response upload(@RequestPart("file") List<MultipartFile> files, @RequestParam(value = "serviceName") String serviceName,@RequestParam(value = "workid") String workid)  {
        return  regulationServie.upLoad(files,serviceName,workid);
   }

    /*
   * @Description 附件下载
   * @Param [file, loadPath]
   * @return org.gocom.coframe.sdk.model.common.Response
   **/
    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public void download(@RequestParam(value = "path") String path, HttpServletResponse response) {
        regulationServie.downLoad(path,response);
    }

/**
 * @ClassName: FileLoadUtils
 * @Description: 附件上传下载工具类
 * @Author yuf
 * @Date 2019/12/20 9:42
 */

@Slf4j
public class FileLoadUtils {

	//附件上传
    public static Response uploadFile(List<MultipartFile> files,String serviceName){
        if(files==null||files.isEmpty()||files.size()==0){
            return new Response("附件为空,请检查");
        }
        List<FileUpload> list = new ArrayList<>();
        for(MultipartFile file:files){
            String fileName= file.getOriginalFilename();
            if(StringUtils.isEmpty(fileName)){
                continue;
            }
            String path = System.getProperties().getProperty("user.home")+File.separator+serviceName;
            String tmpFileName = (Math.random() * 10000 + "").replace(".", "")+"_"+fileName;
            File tempFile = new File(path,tmpFileName);
            //此处设置返回的一些信息,路径,名称,大小,类型等。。。。
         	// fileUpload.set............
            FileUpload  fileUpload = new FileUpload();
            fileUpload.setFileName(tempFile.getName().substring(0,tempFile.getName().lastIndexOf(".")))
       	
            list.add(fileUpload);
            if(!tempFile.exists()){
                tempFile.getParentFile().mkdirs();
                try {
                    tempFile.createNewFile();
                    file.transferTo(tempFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new Response(list);
    }


    /*
     * @Description //文件下载
     * @Param [path, response]
     * @return void
     **/
    public static void downloadFile(String path, HttpServletResponse response) {
        path = System.getProperties().getProperty("user.home")+File.separator+path;
        log.info("【下载附件路径】filename : " + path);
        if (StringUtils.isBlank(path)) {
            log.warn("【附件路径为空】");
            throw new RuntimeException("附件路径为空");
        }
        File myfile = new File(path);
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Length", "" + myfile.length());
        response.setContentType("application/octet-stream");
        OutputStream toClient = null;
        InputStream fis = null;
        //打开文件输入流 和 servlet输出流
        try {
            toClient = new BufferedOutputStream(response.getOutputStream());
            fis = new BufferedInputStream(new FileInputStream(myfile));
            //IOUtils 对接输入输出流,实现文件下载
            IOUtils.copy(fis, toClient);
            toClient.flush();
        } catch (Exception e) {
            log.error("【附件下载失败】", e);
            throw new RuntimeException("附件下载失败");
        } finally {
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(toClient);
        }
    }
}


MultipartFile 转 File
public static File multipartFileToFile(MultipartFile file, String bh) throws Exception {
        if (file.getSize() <= 0) {
            return null;
        }
        File toFile = null;
        // 用户主目录
        String userHome = System.getProperties().getProperty("user.home");
        StringBuilder filepath = new StringBuilder();
        filepath.append(userHome).append(File.separator).append("files").append(File.separator).append(bh).append(File.separator);
        //创建文件夹
        toFile = new File(filepath.toString());
        FileUtils.forceMkdir(toFile);
        //创建文件,此时文件为空
        filepath.append(file.getOriginalFilename());
        toFile = new File(filepath.toString());
        //添加流信息
        file.transferTo(toFile);
        return toFile;
    }
删除File
FileUtils.deleteDirectory(new File(filepath.toString()));
文件流和文件名称转File
public static File inputStreamToFile(InputStream inputStream, String fileName, String bh) throws Exception {
    if (inputStream == null) {
        return null;
    }
    // 用户主目录
    String userHome = System.getProperties().getProperty("user.home");
    StringBuilder filepath = new StringBuilder();
    filepath.append(userHome).append(File.separator).append("files").append(File.separator).append(bh).append(File.separator);
 
    //创建文件夹
    File toFile = new File(filepath.toString());
    FileUtils.forceMkdir(toFile);
 
    //创建文件,此时文件为空
    filepath.append(fileName);
    toFile = new File(filepath.toString());
 
    //为文件添加流信息
    OutputStream os = new FileOutputStream(toFile);
    IOUtils.copy(inputStream, os);
    return toFile;
}
java 文件流的处理 文件打包成zip
1、下载文件到本地
public void download(HttpServletResponse response){
    String filePath ="";//文件路径
    String fileName ="";//文件名称
    // 读到流中
    InputStream inStream = new FileInputStream(filePath);
    // 设置输出的格式
    response.reset();
    response.setContentType("bin");
    response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    IOUtils.copy(inStream, response.getOutputStream());
}
2、java后端下载
方式一:
new URL(fileUrl + item.getcBhFileserver()).openStream()
 
方法二:
    public Boolean addFile(String url, String id, String fileName) {
 
        RequestCallback requestCallBack = new RequestCallback() {
 
            @Override
            public void doWithRequest(ClientHttpRequest request) throws IOException {
                request.getHeaders().add("accept", MediaType.APPLICATION_OCTET_STREAM_VALUE);
            }
        };
 
        ResponseExtractor<Boolean> responseExtractor = new ResponseExtractor<Boolean>() {
 
            @Override
            public Boolean extractData(ClientHttpResponse response) throws IOException {
                if (response.getStatusCode() == HttpStatus.OK) {
                    //得到文件流
                    InputStream input = response.getBody();
                    return true;
                }
                return false;
            }
        };
        return restTemplate.execute(url, HttpMethod.GET, requestCallBack, responseExtractor, id);
    }

3、文件打包成zip

public void zipFilesAll() throws Exception {
        String zipPath = "";//zip包路径
        String zipFileName = "";//zip包名称
        File zipFile = new File(zipFileName .toString());
 
        // 创建 FileOutputStream 对象
        FileOutputStream fileOutputStream = null;
        // 创建 ZipOutputStream
        ZipOutputStream zipOutputStream = null;
        try {
            //创建文件夹
            zipFile = new File(zipPath );
            FileUtils.forceMkdir(zipFile);
 
            //创建文件
            zipFile = new File(zipFileName .toString());
            if (!zipFile.exists()) {
                zipFile.createNewFile();
            }
 
            // 实例化 FileOutputStream 对象
            fileOutputStream = new FileOutputStream(zipFileName.toString());
            // 实例化 ZipOutputStream 对象
            zipOutputStream = new ZipOutputStream(fileOutputStream);
            // 创建 ZipEntry 对象
            ZipEntry zipEntry = null;
            for (CL cl: ClList) {
                // 实例化 ZipEntry 对象,源文件数组中的当前文件
                zipEntry = new ZipEntry(tCltjjl.getcClmc() + ".zip");
                zipOutputStream.putNextEntry(zipEntry);
                IOUtils.copy(new FileInputStream(cl.getcPath(), zipOutputStream);
            }
        } catch (Exception e) {
             
        }finally{
             //删除文件
        }
    }     
根据url获取文件流
一:
InputStream intstream = new URL(url).openStream();

二:
public InputStream getInputStreamByUrl(String strUrl) {
     HttpURLConnection conn = null;
     try {
         URL url = new URL(strUrl);
         conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");
         conn.setConnectTimeout(20 * 1000);
         final ByteArrayOutputStream output = new ByteArrayOutputStream();
         IOUtils.copy(conn.getInputStream(), output);
         return new ByteArrayInputStream(output.toByteArray());
     } catch (Exception e) {
         logger.error("getInputStreamByUrl 异常,exception is {}", e);
     } finally {
         try {
             if (conn != null) {
                 conn.disconnect();
             }
         } catch (Exception e) {
         }
     }
     return null;
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值