java上传下载报错-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

java上传下载报错

DM。 2020-05-27 10:54:16 34

项目发布运行在Tomcat服务器上,文件上传没有问题,路径中的目录也都对,但是在浏览器端下载的时候就出现问题了, 访问到的下载路径中有两个文件夹合并了,代码如下: /** * 文件上传 * @throws IOException */ @RequestMapping("/file/fileUpload.action") public ModelAndView fileUpload(HttpSession session,HttpServletResponse response, @RequestParam("fType") String fType, @RequestParam("uploadfile") List uploadfile, HttpServletRequest request) throws IOException { Student student = (Student)session.getAttribute("USER_INFO"); ModelAndView mv = new ModelAndView(); mv.addObject("fType", fType); if(fType.equals("任务书")) { List list = projBookService.findProjBookBysIdAndAgree(student.getsId(), "待通过"); if(list.size()!=0) { mv.addObject("FAIL", "FAIL1"); mv.setViewName("views/error"); return mv; } }else if(fType.equals("开题报告")) { List list = openReportService.findOpenReportBysIdAndAgree(student.getsId(), "待通过"); if(list.size()!=0) { mv.addObject("FAIL", "FAIL1"); mv.setViewName("views/error"); return mv; } }else if(fType.equals("中期检查")) { List list = midCheckService.findMidCheckBysIdAndAgree(student.getsId(), "待通过"); if(list.size()!=0) { mv.addObject("FAIL", "FAIL1"); mv.setViewName("views/error"); return mv; } }else if(fType.equals("课程设计")) { List list = thesisService.findThesisBysIdAndAgree(student.getsId(), "待通过"); if(list.size()!=0) { mv.addObject("FAIL", "FAIL1"); mv.setViewName("views/error"); return mv; } }else if(fType.equals("附件")) {

List<ThesisAttachment> list = thesisAttachmentService.findThesisAttachmentBysId(student.getsId());
        if(list.size()!=0) {
            mv.addObject("FAIL", "FAIL1");
            mv.setViewName("views/error");
            return mv;
        }
    }
    student = studentService.findStudent(student.getsId(), student.getsPwd());
    Title title = titleService.findTitleBysId(student.getsId());
    String tId = title.gettId();
//  String tName = title.gettName();
    String t = tId;
    String s = student.getsId() + student.getsName();
    s = s + fType;

    // 判断所上传文件是否存在
            if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
                //循环输出上传的文件
                for (MultipartFile file : uploadfile) {
                    String name1 = t;
                    // 获取上传文件的原始名称
                    String originalFilename = file.getOriginalFilename();
                    System.out.println("上传文件原始文件名是: "+ originalFilename);
                    int c = originalFilename.indexOf(".");
                    String s1 = originalFilename.substring(c);
                    String s2 = originalFilename.substring(0, c);
                    s2 = s;
                    originalFilename = s2 + s1;
                    //获取上传文件后缀名
                    String dirPath = 
                           request.getServletContext().getRealPath("/upload"+name1);
                    System.out.println(dirPath);
                    File filePath = new File(dirPath);
                    // 如果保存文件的地址不存在,就先创建目录
                    if (!filePath.exists()) {
                        filePath.mkdirs();
                    }
                    String newFilename = dirPath + "\\" + originalFilename;
                    System.out.println("文件保存地址" + newFilename +"\n");
                    File filePath2 = new File(newFilename);
                    int i = 0;
                    String s3 = null;
                    while(filePath2.exists()) {
                        i++;
                        s3 = s2+ "(" + String.valueOf(i) +")";
                        originalFilename = s3 + s1;
                        System.out.println("文件已存在,重新命名为: "+originalFilename);  //文件名
                        newFilename = dirPath + "\\" + originalFilename;
                        System.out.println("新文件地址是: " +newFilename);
                        filePath2 = new File(newFilename);
                    }
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    String nowtime = df.format(new Date());
                    System.out.println(nowtime);// new Date()为获取当前系统时间
                    try {
                        // 使用MultipartFile接口的方法完成文件上传到指定位置
                        file.transferTo(new File(newFilename));
        //              String newFilenamePdf = s3 + ".pdf";
        //              System.out.println("生成的pdf文件名是: "+ newFilenamePdf);
        //              newFilenamePdf = dirPath + "\\" + newFilenamePdf;
        //              System.out.println("生成的pdf文件的保存地址是: "+newFilenamePdf);
        //              WordToPdf w = new WordToPdf();
        //              w.wordToPDF(newFilename, newFilenamePdf);
                        Myfile myfile = new Myfile();
                        myfile.setfName(originalFilename);                           
                        myfile.setfPath(newFilename);
                        Date date = df.parse(nowtime);
                        myfile.setUploadDatetime(date);
                        myfile.setfType(fType);
                        myFileService.createMyfile(myfile);

/**
 * 文件下载
 */
@RequestMapping("/file/filedown.action")
public ResponseEntity<byte[]> downfile(HttpSession session, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String fId = request.getParameter("fId");
    ProjBook projBook = null;
    Myfile myfile = new Myfile();
    long l = Long.parseLong(fId);
    myfile = fileService.selectById(l);
    String filename = myfile.getfName();
    projBook = projBookService.findProjBookByfId(l);
    User user =(User) session.getAttribute("USER");
    String path = null;
    if(user.getRole().equals("学生")) {
        System.out.println("进来了");
        Student student = (Student) session.getAttribute("USER_INFO");
        List<ProjBook> list = projBookService.findProjBookList(projBook, (String) student.getsId());
        String tId = list.get(0).gettId();
        String tName = list.get(0).gettName();
        System.out.println(tId);
        System.out.println(tName);
        tName = tId;
        path = request.getServletContext().getRealPath("/upload");
        path = path + tName + "\\";
    }
    else if(user.getRole().equals("教师")) {
        String tId = request.getParameter("tId");
        String tName = request.getParameter("tName");
        tName = tId;
        path = request.getServletContext().getRealPath("/upload");
        path = path + tName + "\\";
    }
    System.out.println("地址是 " + path);
    // 指定要下载的文件所在路径
    ResponseEntity<byte[]> result = null;
    try {
        // 创建该文件对象
        File file = new File(path + File.separator + filename);
        // 对文件名编码,防止中文文件乱码
        filename = this.getFilename(request, filename);
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 通知浏览器以下载的方式打开文件
        headers.setContentDispositionFormData("attachment", filename);
        // 定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 使用Sring MVC框架的ResponseEntity对象封装返回下载数据
        result = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print("<script language=\"javascript\">alert('下载失败!')</script>");
    } catch (IOException e) {
        e.printStackTrace();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print("<script language=\"javascript\">alert('下载失败!')</script>");
    }
    return result;
}

报错信息 上传文件原始文件名是: 任务书.docx D:\apache-tomcat-7.0.72\webapps\Course-Design-Management-System\upload\20080044 文件保存地址D:\apache-tomcat-7.0.72\webapps\Course-Design-Management-System\upload\20080044\1608010111吴勇任务书.docx 2020-05-18 22:12:18 进来了 20080044 王老师 地址是 D:\apache-tomcat-7.0.72\webapps\Course-Design-Management-System\upload20080044
java.io.FileNotFoundException: File 'D:\apache-tomcat-7.0.72\webapps\Course-Design-Management-System\upload20080044\1608010111吴勇任务书.docx' does not exist

Java
分享到
取消 提交回答
全部回答(2)
  • huc_逆天
    2020-05-27 13:37:38

    需要检查下,在何时,因为那个代码,让文件夹产生了合并,导致目录结构发生改变

    0 0
  • DM。
    2020-05-27 13:38:04

    D:\apache-tomcat-7.0.72\webapps\Course-Design-Management-System\upload\20080044\1608010111吴勇任务书.docx 'D:\apache-tomcat-7.0.72\webapps\Course-Design-Management-System\upload20080044\1608010111吴勇任务书.docx 这两个地址明显不一样吧,upload\20080044下载的时候,这里配置是不是少了个\ 肯定是你配置有问题,仔细检查下下载访问路径

    0 0
添加回答
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

推荐文章
相似问题