文件处理(上传、下载等,基于七牛)

一、文件上传

页面type为file的input标签,提交到后台的文件可以用request获取,获取后的是mutipleFile类型,可以直接getbyte获取其字节,再调用接口上传至七牛

    public JsonResponse<String> uploadFile(MultipartFile file) {
        JsonResponse<String> response = new JsonResponse<String>();
        try {
            if(file.getBytes().length==0||StringUtils.isBlank(file.getOriginalFilename())){
                response.setStatus(ResponseInfo.ERROR.getStatus());
                response.setMsg("文件上传错误!请重新上传!");
                return response;
            }
            String fileUploadMsg = fileUpload(file.getBytes(), file.getOriginalFilename());
            if(FileUtil.isFileId(fileUploadMsg)){
                response.setData(fileUploadMsg);
                return response;
            }else{
                response.setStatus(ResponseInfo.ERROR.getStatus());
                response.setMsg(fileUploadMsg);
                return response;
            }
        } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(ResponseInfo.ERROR.getStatus());
            response.setMsg("文件上传失败!请重新上传!");
            return response;
        }
    }```
```@Override
    public String fileUpload(byte[] data, String originalFileName) {
        if(StringUtils.isBlank(originalFileName)){
            return "文件名称为空";
        }
        if(data.length > 10485760){//单个文件不可以超过10M
            return "文件过大";
        }
        String ext = originalFileName.substring(originalFileName.lastIndexOf(".")+1);
        String regex = "^JPG|JEPG|PNG|DOC|DOCX|PDF$";
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);//忽略大小写
        if(!pattern.matcher(ext).matches()){
            return "文件格式不正确";
        }
        //eg_file表创建一条记录
        File file = new File();
        file.setFileId(IdWorker.nextId(ModelPrefix.FILE));      
        String fileName = originalFileName.substring(0,originalFileName.lastIndexOf("."));
        file.setFileName(fileName);
        file.setExt(ext);
        file.setByteCount(data.length); 
        fileMapper.insertSelective(file);
        try{
            FileUtil.fileUploadByByteArray(data, file.getFileId());
            return file.getFileId();
        }catch(Exception e){
            fileMapper.deleteByPrimaryKey(file.getFileId());
            e.printStackTrace();
        }
        return null;
        
    }```
##二、文件下载
####先页面请求获取七牛里文件的地址url
```@Override
    public JsonResponse<String> getDownloadUrlByFileId(String fileId) {
        JsonResponse<String> response = new JsonResponse<String>();
        if(StringUtils.isBlank(fileId)){
            response.setStatus(ResponseInfo.ERROR.getStatus());
            response.setMsg("文件编号不能为空!");
            return response;
        }
        File file = new File();
        file.setFileId(fileId);
        file = fileMapper.selectByPrimaryKey(file);
        if(file!=null&&StringUtils.isNotBlank(file.getFileName())&&StringUtils.isNotBlank(file.getExt())){
            String fileName=file.getFileName()+"."+file.getExt();
            try {
                String fileUrl = FileUtil.getFileUrl(fileId, fileName);
                response.setData(fileUrl);
                return response;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            response.setStatus(ResponseInfo.ERROR.getStatus());
            response.setMsg("文件不存在!");
            return response;
        }
        return response;
    }```
####再次请求上面获得的地址,即可下载文件。此处做异步下载,以标签a的形式在前端实现
          scope.downloadFile=function(){
              if(scope.egFileId){
                  var url=__ctx+"/file/getDownloadUrlByFileId/"+scope.egFileId;
                  //获取文件名
                  $http.get(url).success(function(data){
                      if(data.status==0){
                          if (navigator.userAgent.indexOf('Firefox') >= 0){
                              //解决火狐浏览器不兼容问题
                              var b=window.open();
                              setTimeout(function(){
                              b.location=data.data;
                              }, 200);
                          }else{
                              var elementObj= document.createElement("a");
                              elementObj.href = data.data;
                              elementObj.click();
                          }
                        
                      }
                  })
              }
          }```

三、也可做同步下载(不推荐,响应时间较长)

页面发送请求给服务器,服务器先获取url,再向url请求到文件并返回页面

public static ResponseEntity<byte[]> downLoadWithGet(String url,String fileName,String ext) throws Exception{
         CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpGet httpget = new HttpGet(url);
                httpget.setHeader("Accept-Encoding", "identity");
                HttpResponse response = httpclient.execute(httpget);
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024*10];
                    InputStream is = entity.getContent();
                    int len = 0;
                    while((len=is.read(buffer))!=-1){
                        outStream.write(buffer,0,len);
                    }
                    outStream.close();
                    is.close();
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                    headers.setContentLength(entity.getContentLength());
                    headers.setContentDispositionFormData("attachment", fileName+"."+ext); 
                    return new ResponseEntity<byte[]>(outStream.toByteArray(),headers, HttpStatus.CREATED);
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
                
            } finally {
                httpclient.close();
            }
    }```

推荐阅读更多精彩内容