码迷,mamicode.com
首页 > Web开发 > 详细

上传下载文件

时间:2020-05-16 22:21:12      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:前端   sub   Servle   indexof   coder   puts   exists   def   length   

上传下载文件

依赖

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

上传 方式一(原生)

//判断上传文件是普通表单还是带文件的表单
if(!ServletFileUpload.isMultipartContent(request)){
    return;
}
//创建上传的保存路径  如果不存在则创建
String filePath = this.getServletContext().getRealPath("/WEB-INF/upload");
File uploadFile = new File(filePath);
if(!uploadFile.exists()){

    uploadFile.mkdir();
}

//缓存,临时文件
//临时路径,进入超过了预期大小,放到零时文件中,过几天删除,或提醒用户转存为永久
String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
File tempFile = new File(tempPath);
if(!tempFile.exists()){
    tempFile.mkdir();
}



//处理上传文件,一般需要通过流来获取,我们可以使用request。getInputStream()原生态上传流获取,很麻烦
//但是我们都建议使用apache的文件上传来实现,common-fileupload,需依赖common-io组件

DiskFileItemFactory factory = getDiskFileItemFactory(tempFile);
ServletFileUpload upload = null;
try {
    upload = getServletFileUpload(factory,request);
} catch (FileUploadException e) {
    e.printStackTrace();
}
try {
    String msg = uploadParseRequest(request, upload, filePath);
    request.setAttribute("msg",msg);
    request.getRequestDispatcher("info.jsp").forward(request,response);
} catch (Exception e) {
    e.printStackTrace();
}
public DiskFileItemFactory getDiskFileItemFactory(File file){
    //1.创建DiskFileItemFactory对象,处理文件上传路径或者大小限制
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //下面的两行代码有默认值,非必须
    //通过这个工厂设置缓冲区,当上传文件大于这个缓冲区的时候,将她放在临时文件中。
    factory.setSizeThreshold(1024*1024);//大小为1M
    factory.setRepository(file);//临时目录的保存目录,需要一个tempFile

    return factory;
}
public ServletFileUpload getServletFileUpload(DiskFileItemFactory factory,HttpServletRequest request) throws FileUploadException {
    //2.获取ServletUpload
    ServletFileUpload upload = new ServletFileUpload(factory);
    //监听上传进度
    //可以用来做进度条
    //下面七行代码非必须

 //判断大小
    List<FileItem> fileItems = upload.parseRequest(request);

    for (FileItem fileItem : fileItems) {

        if(fileItem.getSize()>1024*1024*10){

            System.out.println("太大了,返回");
            return upload;
        }
    }



    upload.setProgressListener(new ProgressListener(){

        @Override
        public void update(long pBytesRead,long pContentLength,int pItems){


                System.out.println("总大小"+pContentLength+"已上传"+pBytesRead);


        }

    });



    //处理乱码问题
    upload.setHeaderEncoding("UTF-8");
    //总共单个的文件大小
   upload.setFileSizeMax(1024*1024*10);
    //总共能够上传文件的大小
    upload.setSizeMax(1024*1024*10);

     return upload;
}
public String uploadParseRequest(HttpServletRequest request,ServletFileUpload upload,String filePath) throws Exception {

    String msg = "";
    List<FileItem> fileItems = upload.parseRequest(request);
    for (FileItem fileItem : fileItems) {

        /*if(fileItem.getSize()>1024*1024*10){
            msg="太大了,不行";
            return msg;
        }*/
       // System.out.println(fileItem.getSize());
        //判断为普通表单还是带文件的表单
        if (fileItem.isFormField()) {

            String name = fileItem.getFieldName();//前端控件的name
            String value = fileItem.getString("UTF-8");
            System.out.println(name + ":" + value);
        } else {

            System.out.println(fileItem.getSize());
            //判断文件大小
            /*if(fileItem.getSize()>1024*1024*10){
                msg="上传失败,文件过大";
                System.out.println(msg);
                return msg;
            }*/
            //处理文件
            String fileItemName = fileItem.getName();

            //名字不合法
            if (fileItemName == null || fileItemName.trim().equals("")) {

                continue;
            }
            //获得文件名
            String fileName = fileItemName.substring(fileItemName.lastIndexOf("/") + 1);
            //获得后缀名
            String fileExtName = fileItemName.substring(fileItemName.lastIndexOf(".") + 1);

            String uuidPath = UUID.randomUUID().toString();
            String realPath = filePath + "/" + uuidPath;
            File realPathFile = new File(realPath);
            if (!realPathFile.exists()) {
                realPathFile.mkdir();
            }
            //存放地址
            //文件传输
            //或的文件上传的流
            InputStream inputStream = fileItem.getInputStream();

            //创建一个文件输出的流
            FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);
            //创建缓冲区
            byte[] buffer = new byte[1024 * 1024];

            //判断是否读取完毕
            int len = 0;
            while ((len = inputStream.read(buffer)) > 0) {

                fos.write(buffer, 0, len);

            }
            fos.close();
            inputStream.close();
            msg = "文件上传成功";
            //上传成功 清除零时文件
            fileItem.delete();
        }
    }
    System.out.println(msg);
    return msg;

}

方式二 (配置版)

在application-context.xml中配置

<!--文件上传配置-->
<!--id必须为 multipartResolver-->
<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,
    默认为ISO-8859-1 -->
    <property name="defaultEncoding" value="utf-8"/>
    <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40960"/>
</bean>

方式一

 @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//获取文件名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();
//如果文件名为空,直接回到首页!
        if ("".equals(uploadFileName)) {
            return "../../index";
        }
        System.out.println("上传文件名 : " + uploadFileName);
//上传路径保存设置
        String path = request.getSession().getServletContext().getRealPath("/upload");


//如果路径不存在,创建一个
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址:" + realPath);
        InputStream is = file.getInputStream(); //文件输入流
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); //文件输出流读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();
        return "../../index";
    }

方式二 直接新建文件夹 读取并写入

@RequestMapping("/upload2")
    public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存设置
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
//上传文件地址
        System.out.println("上传文件保存地址:" + realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
        file.transferTo(new File(realPath + "/" +
                file.getOriginalFilename()));
        return "../../index";
    }

下载文件

 @RequestMapping(value = "/download")
    public String downloads(HttpServletResponse response, HttpServletRequest
            request) throws Exception {
//要下载的图片地址
        String path = request.getSession().getServletContext().getRealPath("/upload");
        String fileName = "整合.md";
//1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
//设置响应头
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path,fileName);
//2、 读取文件--输入流
        InputStream input=new FileInputStream(file);
//3、 写出文件--输出流
        OutputStream out = response.getOutputStream();
        byte[] buff =new byte[1024];
        int index=0;
//4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return null;
    }

前端

<a href="/download">点击下载</a>

上传下载文件

标签:前端   sub   Servle   indexof   coder   puts   exists   def   length   

原文地址:https://www.cnblogs.com/wsxultimate/p/12902489.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!