下载代码和上传(以及文件名是乱码解决)

自己总结一下代码中的下载思路....

 前端页面的写法

 // 下载
    function downLoad(id) {
        var downloadStr = encodeURI(apiUrl + '/downLoadDoc?&_jspage=' + utils.getUrlPath()+'&id='+id);
        window.location.href = downloadStr;
    }

后端下载代码

    @RequestMapping(path = "/downLoadDoc",method = RequestMethod.GET)
     public ResponseEntity downLoadDoc(HttpServletRequest request, HttpServletResponse response) {
        log.info("下载");
        try{

            String id = request.getParameter("id");
            String path = oaDocumentDao.findOne(id).getFileUrl();
            // path是指欲下载的文件的路径。
            File file = new File(path);

            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header  设置编码 防止乱码出现
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"),"ISO-8859-1"));
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            response.getOutputStream().write(buffer);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

防止乱码:文件下载中文文件名乱码问题解决_filebody文件名乱码_你认识小汐吗的博客-CSDN博客

1、首先后台接收后,多文件名进行再编码

filePath = new String(filePath.getBytes(),"utf-8");//有没有这句话
2、注意设置浏览器,很重要
 

//浏览器设置
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {  
	//IE浏览器处理
	fileName = java.net.URLEncoder.encode(fileName, "UTF-8");  
} else {  
	// 非IE浏览器的处理:  
	fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");  
} 
// 设置文件头:最后一个参数是设置下载文件名
response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
// 设置文件ContentType类型,这样设置,会自动判断下载文件类型  
response.setContentType("application/octet-stream;charset=utf-8");
 
//流对拷
OutputStream os = response.getOutputStream();
int len = 0;
byte[] b = new byte[1024];
while ((len = is.read(b)) > 0) {
	os.write(b, 0, len);
}
 
os.close();
is.close();

上传功能

// 前端ajax上传
<script>
function uploadHead() {
		var formData = new FormData();
		var file = $('#file')[0].files[0];
		formData.append("upload",file);
		$.ajax({
			url:"/uploadHead",
			async:true,
			processData: false,   // jQuery不要去处理发送的数据
			contentType: false,   // jQuery不要去设置Content-Type请求头
			type:"POST",
			data: formData,
            dataType:"json",
			success:function (data) {
				
			}
		
		});


 
</script>
<input type="file" name="multipartFile" class="fileInput" id="file" >
<input type="button" onclick="uploadHead();">


 /**
     * 上传文件
     * @param upload
     * @param path
     * @return
     * @throws IOException
     */
    public String UploadFile(MultipartFile upload,String path) throws IOException {
        //判断该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            //如果这个文件夹不存在的话,就创建这个文件
            file.mkdirs();
        }
        //获取上传文件名称
        String filename = upload.getOriginalFilename();
        System.out.println(filename);
        //把文件名称设置成唯一值 uuid 以防止文件名相同覆盖
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //新文件名
        filename = uuid + "_" + filename;
        System.out.println(filename);
        //完成文件上传
        upload.transferTo(new File(path, filename));
        String filePath = "upload/" + filename;
        return filePath;
    }

//这里的话是已经将文件上传并即将图片记录在数据库并更换(mybatis)
@RequestMapping("uploadHead")
    public void ReturnHead(HttpServletRequest request, HttpServletResponse response, MultipartFile upload) throws IOException {
        User userSession = (User) request.getSession(true).getAttribute("userSession");
        OperateFile operateFile = new OperateFile();
        if (userSession!=null){
            String path = ResourceUtils.getURL("classpath:").getPath() + "static/upload";
            //System.out.println(path);
            String filePath = operateFile.UploadFile(upload,path);//文件上传成功
            String filename = upload.getOriginalFilename();
            String fileUuid = UUID.randomUUID().toString().replace("-", "");
            Img img = new Img();//进行图片记录
            img.setUuid(fileUuid);
            img.setImg_name(filename);
            img.setImg_type(1);
            img.setImg_path(filePath);
            img.setNote(userSession.getUuid()+"用户上传");
            int c = userService.addImg(img);
            if (c>0){
                User u1 = new User();
                u1.setUuid(userSession.getUuid());
                u1.setImg_uuid(fileUuid);
                int c1 = userService.updateHead(u1);
                if (c1>0){
                    response.getWriter().write("1");
                }else{
                    response.getWriter().write("0");
                }
            }else{
                response.getWriter().write("0");
            }
        }
    }

$.ajax({
                        type: "POST",
                        url: urlPath + '/importSealStatus',
                        contentType: false, // 注意这里应设为false
                        processData: false,
                        cache: false,
                        dataType: "json",
                        data: formData,
                        success: function (retdata) {
                            window.parent.layer.msg("导入成功!");
                            window.parent.layer.close(index);
                            doFresh();
                        },
                        error: function (xmlhttp, textStatus, errorThrown) {
                            var o = JSON.parse(xmlhttp.responseText);
                            window.parent.layer.msg(o.message, {icon: 5});
                        }
                    });
	}
// 后端接口 
 @RequestMapping(path = "/importSealStatus", method = RequestMethod.POST)
    public ResponseEntity importSealStatus(@RequestParam MultipartFile file, HttpSession session) throws IOException {

        StringBuilder json = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
            CharBuffer buffer = CharBuffer.allocate(1024);
            while (reader.read(buffer) != -1) {
                json.append(buffer.flip());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        SealStatusDataPack pack; //自己的实体类
        User loginUser = (User) session.getAttribute("loginUser");
        if ((pack = JsonUtil.jsonToObject(json.toString(), SealStatusDataPack.class)) != null) {
            try {
                if (!SealPackConverter.verify(pack)) {
                    return new ResponseEntity<>(new Response<>(ERR_LOGIN_SIGNED_REFUSE), HttpStatus.BAD_REQUEST);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            List<SealValidTimeHistory> sealList = SealPackConverter.deSerialize(pack);
            sealValidTimeHistoryDao.save(sealList);
        }
        return new ResponseEntity<>(null, HttpStatus.OK);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值