Sakura Warring 2020-05-19 08:52 采纳率: 100%
浏览 118
已采纳

java上传下载出现问题

项目发布运行在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

  • 写回答

1条回答 默认 最新

  • Joker_Wanghy 2020-05-19 09:16
    关注

    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下载的时候,这里配置是不是少了个\ 肯定是你配置有问题,仔细检查下下载访问路径

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 依据报错在原代吗格式的基础上解决问题
  • ¥15 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?