文件的上传与下载

心得:本人觉得,不论是上传还是下载都不要在js里使用ajax请求,可以使用表单提交的方式代为发送请求。

 

一、Input 文件上传

1、前端代码:---HTMl

<button v-if="item.egis == 2" class="btn btn-wide btn-darker-1" @click="toUpload(index)">上传</button>
<!-- <button v-if="item.egis == 2" class="btn btn-wide btn-darker-1" onclick="toUpload(index)">上传</button> -->
<!--可以让大家共同调用,没必要每条记录里都加个上传按钮-->
<input id="file" type="file" name="file" onchange="chooseFile(this);" placeholder="上传附件" autocomplete="off" style="display: none">

---JS var page
= new Vue(   el: "#page", data: {...},   method:{ // 因为想引用这个下标,所以使用了Vue语法 @click,需要注意的是这样使用的时候不能通过jQuery的${this}获取到当前元素 // 如果想获取到当前元素,可以使用原生的onclick()方法,但是此种情况下不能再使用vue里的index下标,并且toUpload()方法要定义到Vue外部     toUpload(index) {   $("#file").trigger("click"); },   }, ) // 模拟input的单击事件选择文件 function chooseFile(i){ let oMyForm = new FormData(); oMyForm.append("file", i.files[0]); $.ajax({ url: '/upload/salaryFile', type: 'POST', cache: false, data: oMyForm, processData: false, contentType: false, async: false }).done(function(res) { page.fileUrl = res; }).fail(function(res) { console.log("文件上传失败") }); };

 

 

2、后台代码(上传阿里云OSS):

@RequestMapping(value = "/salaryFile")
@ResponseBody
public ResultModel addSalaryFile(MultipartFile[] file) {
String fileName = "";
if(EmptyUtils.isNotEmpty(file)){
byte[] bytes =null;
try {
String name=file[0].getOriginalFilename();
String format = name.substring(name.indexOf(".")+1);
bytes=file[0].getBytes();
String fileName_last = OssUtil.uploadByte(bytes, OssConstant.PUBLIC_BUCKET, OssConstant.Salary,format);
fileName = PREFIX + OssConstant.Salary+ "/" + fileName_last;
} catch (IOException e) {
e.printStackTrace();
}
}
return result(fileName);
}

public static String uploadByte(byte[] content,String bucket,String folderName,String format){
OSSClient ossClient = getOSSClient();
String fileName = generateName() +"."+ format;
ossClient.putObject(bucket,getObjectName(folderName, fileName), new ByteArrayInputStream(content));
ossClient.shutdown();
return fileName;
}

 

 

二、文件下载

1、前端代码:

<button v-if="item.egis == 2 && item.fileUrl != null" class="btn btn-wide btn-darker-1" @click="toDownload(item.id)">下载</button>
<%--下载附件--%> <form action="download" method="post" style="display: none;" id="download"> <div> <input type="hidden" class="form-control" name="wagesId" id="wagesId_download"> </div> </form> // 下载附件
toDownload(wagesId) {
  $(
"#wagesId_download").val(wagesId);
  $(
'#download').submit();
  
// 不能使用ajax请求
  // $.post(api.downloadFile, {wagesId:wagesId,}, function(data) {});
},

 

2、后台代码(输出流下载文件,返回值设置成void,避免继续往前台传输数据造成报错):

/**
     * @description 下载已经上传的附件
     * @author tank
     * @date 2019/8/23 14:25
     */
    @PostMapping("/download")
    @ResponseBody
    public void download(HttpServletResponse response, HttpServletRequest request, String wagesId) throws IOException {
        if(EmptyUtils.isEmpty(wagesId)){
            return;
        }
        // 根据id去数据库中查找fileUrl,OSS里存储在salary文件夹
        String fileUrl = salaryEditService.getFileUrlById(wagesId);
        // 通过Oss方法将文件转化成String字符串
        String lastName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);

        // 获取所有盘符,将文件保存在最后一个盘符的根目录下,可以保存成功但是用户不知道
        /*File[] roots = File.listRoots();
        String localFolderName = roots[roots.length-1].toString();
        OssUtil.downloadFile(OssConstant.PUBLIC_BUCKET, OssConstant.Salary,lastName,localFolderName);
        */
        // 从阿里云对象存储下载到服务器,再通过服务器由浏览器下载
        String targetPath = CommonMethod.getProjectPath(request)+Constants.FILE_HETONG +"\\";
        OssUtil.downloadFile(OssConstant.PUBLIC_BUCKET, OssConstant.Salary,lastName,targetPath);

        HttpServletRequest httpRequest=(HttpServletRequest)request;
        //获取文件
        File file = new File(targetPath+lastName);
        response.reset();

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");//octet-stream为二进制类型,适用所有文件
            response.setHeader("Content-disposition", "attachment; filename=" + lastName);
            response.setHeader("Content-Length", String.valueOf(file.length()));
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))){
                bos.write(buff, 0, bytesRead);
            }
            bos.flush();
        } catch (Exception e) {
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
                file.delete();
            } catch (Exception e) {
            }
        }
    }

 

posted @ 2019-08-23 12:43  tank073  阅读(200)  评论(0)    收藏  举报