实现文件上传文件的地址的获取手段之一IO流读取

这是为了我方便之后来查询的代码:

该文件上传是使用form表单提交到后台再使用io流读取,获得文件路径;待修改和完善

package cn.edu.web.servlet;

import cn.edu.pojo.Course;
import cn.edu.service.CourseListService;
import cn.edu.service.CourseListServiceImpl;
import com.google.gson.Gson;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/AlterCourseServlet")
public class AlterCourseServlet extends HttpServlet {

    //创建对象调用根据课程id修改课程信息的方法
    CourseListService courseListService = new CourseListServiceImpl();

    //创建course对象
    Course course = new Course();

    //用于存储文件满足的所有格式
    Map<String,String> map = null;

    //文件的格式后缀名  陈必成
    String extensionName = null;

    //文件格式是否符合要求 而定义的变量
    String message = null;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理中文乱码 由于是使用io流读取,这个对于获取来说没用,但可以用以转发的情况处理乱码
        response.setContentType("text/html;charset=UTF-8");

        //判断是不是传入的一个二进制的流
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //创建一个简单工厂实例
        FileItemFactory factory = new DiskFileItemFactory();
        //创建一个新的文件上传处理程序
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解析request
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            //处理上传的项目
            Iterator iter = fileItems.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
//                    //普通域
                    processFormField(item);
                } else {
                    //文件域  此处注意processUploadFile()方法的参数里面传入request的目的是让下面写文件的时候获取根目录用的
                    processUploadFile(item, request);

                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        ServletInputStream inputStream = request.getInputStream();
        byte[] bs = new byte[1024];
        int total = -1;
        while ((total = inputStream.read(bs)) != -1) {
            System.out.print(new String(bs, 0, total));
        }
        //获取根路径

        String path = request.getContextPath();
        System.out.println("根路径:"+path);

        //获取添加时间
        //获取时间
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Gson gson = new Gson();

        //将course获得的修改后的课程信息保存到对应课程id的课程信息上

        System.out.println("获取到的修改课程信息:"+gson.toJson(course));

        int i = courseListService.updateByExampleSelective(course);
        if(i>0){
            System.out.println("修改成功");
        }

    }

    /**
     * 文件域
     *
     * @param item
     * @param request
     */
    private void processUploadFile(FileItem item, HttpServletRequest request) {
        //获取文件相关信息
        String fileName = "";
        if (!item.isFormField()) {
            String fieldName = item.getFieldName();
            fileName = item.getName();
//            int split = fileName.lastIndexOf(".");
//            String first = fileName.substring(0, split) + System.currentTimeMillis();
//            fileName = first + fileName.substring(split);
//            String contentType = item.getContentType();
//            long sizeInBytes = item.getSize();
//            System.out.println("\n文件名: " + fileName + "\n 文件属性:" + fieldName + "\n 文件大小:" + sizeInBytes + "\n 文件类型:" + contentType);

            //获取扩展名  陈必成  通过String的subString方法 和lastIndexOf(".")
            extensionName = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
//            System.out.println("该文件的扩展名:"+extensionName);

            //验证是否格式正确  陈必成
            map = new HashMap<String,String>();
            map.put("jpg","jpg");
            map.put("jpeg","jpeg");
            map.put("png","png");
            map.put("bmp","bmp");
            map.put("gif","gif");
            map.put("mp4","mp4");
            map.put("asx","asx");
            map.put("asf","asf");
            map.put("mpg","mpg");
            map.put("3gp","3gp");
            map.put("mov","mov");
            map.put("avi","avi");
            map.put("flv","flv");
            map.put("wmv","wmv");

        }

        // 文件后缀判断
        if (!map.containsKey(extensionName)) {
            System.out.println(extensionName);
            message = "输入文件格式不正确";
            // 文件读入

        }else{

            //对于上传文件的判断
            if(extensionName.equals("jpg")||extensionName.equals("bmp")||extensionName.equals("png")||extensionName.equals("jpeg")){
                //上传的是仅支持 jpg bmp png jpeg格式的图片  陈必成
                //以下是转存操作,找到对应储存文件的根路径
                String fileRootPath = request.getServletContext().getRealPath("/images/upload/course");
                File dir = new File(fileRootPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                //写文件  注释掉第一种写法,尝试第二种写法
                File file = new File(fileRootPath + "/" + fileName);
                //写文件
                String s = "/images/upload/course/" + fileName;
                try {
                    //将图片存入硬盘指定位置
                    item.write(file);

//                    System.out.println("项目路径:"+s);

                    message = "保存成功";
//            将图片路径封装进去 等会再一起放入数据库
//                    course.setLogo(s);

//                    System.out.println("图片路径:"+s);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }else if(extensionName.equals("mp4")){
                //上传的是仅支持 mp4 格式的视频

                //以下是转存操作,找到对应储存文件的根路径
                String fileRootPath = request.getServletContext().getRealPath("/video/upload/course");
                File dir = new File(fileRootPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                //写文件  注释掉第一种写法,尝试第二种写法
                File file = new File(fileRootPath + "/" + fileName);
                //写文件
                String s = "/video/upload/course/" + fileName;
                try {
                    //将视频存入硬盘指定位置
                    item.write(file);
                    //在后台输出视频路径---此处是项目路径
//                    System.out.println("项目路径:" + s);

                    message = "保存成功";
//            将视频路径封装进去等会 放进数据库

//                    kpoint.setVideourl(s);
//
//                    course.setKpoint(kpoint);
//                    System.out.println("视频路径:"+s);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        System.out.println(message);

    }

    /**
     * 普通域
     *
     * @param item
     */
    private void processFormField(FileItem item) {
        String key = item.getFieldName();
        String value = null;
        try {
            //处理中文乱码
            value = item.getString("gb2312");

            switch (key) {

                case "course_num":

                    //这里是课程id的获取,并对其修改

                    System.out.println(value);
                    course.setCourseid(Integer.parseInt(value));
                    break;
                case "course_name":
                    //这里是课程名称的获取,并对其修改
                    course.setCoursename(value);

                    break;
                case "course_classify":
                    //这里是课程分类的获取,并对其修改
                    course.setCoursetype(value);

                    break;
                case "sourcePrice":
                    //这里是课程原价的获取,并对其修改
                    course.setSourceprice(Double.parseDouble(value));

                    break;

            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        System.out.println("刷新....");
    }

    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("初始化....");
    }

}

Servlet

原文地址:https://www.cnblogs.com/bichen-01/p/11830276.html

时间: 2024-07-31 22:48:06

实现文件上传文件的地址的获取手段之一IO流读取的相关文章

java 大文件上传 断点续传 完整版实例 (Socket、IO流)

原文出自:https://blog.csdn.net/seesun2012 java两台服务器之间,大文件上传(续传),采用了Socket通信机制以及JavaIO流两个技术点,具体思路如下: 实现思路: 1.服:利用ServerSocket搭建服务器,开启相应端口,进行长连接操作 2.服:使用ServerSocket.accept()方法进行阻塞,接收客户端请求 3.服:每接收到一个Socket就建立一个新的线程来处理它 4.客:利用Socket进行远程连接,询问已上传进度 5.客:使用File

SWFUpload多文件上传 文件个数限制 setStats()

使用swfupload仿赶集的图片上传 SWFUpload是一个基于flash与javascript的客户端文件上传组件. handlers.js文件 完成文件入列队(fileQueued) → 完成选择文件(fileDialogComplete) → 开始上传文件(uploadStart) → 上传处理(uploadProgress) → 上传成功(uploadSuccess) → 上传完成(uploadComplete)  → 列队完成(queueComplete) 如上所示,单选文件顺序执

CI支持各种文件上传-文件类型(Linux + window)

$mimes = array( 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv'

通达OA 任意文件上传+文件包含导致RCE漏洞复现

0X00漏洞简介 通达OA(Office Anywhere网络智能办公系统)是由北京通达信科科技有限公司自主研发的协同办公自动化系统,包括流程审批.行政办公.日常事务.数据统计分析.即时通讯.移动办公等. 该漏洞被黑产利用,用于投放勒索病毒 该漏洞在绕过身份验证的情况下通过文件上传漏洞上传恶意php文件,组合文件包含漏洞最终造成远程代码执行漏洞,从而导致可以控制服务器system权限. 0X01漏洞影响 V11版.2017版.2016版.2015版.2013增强版.2013版 0X02漏洞原理

IE8 文件上传文件为空的问题

今天在使用之前做的应用系统时发现原来能使用的文件上传今天突然不能使用了,换了浏览器试了下原来是IE8的问题,firefox.chrome倒是没有这种问题,网上查了下原来又是IE8的问题,真是崩溃了... IE8基于安全的考虑,文件上传只允许鼠标的点击触发文件浏览及上传.如果是通过js触发的文件浏览就会导致上传失败(默认的input[type=file]的样式太差,与现有系统不一致,所以大多系统开发时会使用自定义的浏览按钮通过js调用原input[type=file]的onclick或者oncha

django中处理文件上传文件

1 template模版文件uploadfile.html 特别注意的是,只有当request方法是POST,且发送request的<form>有属性enctype="multipart/form-data"时,request.FILES中包含文件数据,否则request.FILES为空. <form method="post" action="" enctype="multipart/form-data"

struts文件上传——文件过大时错误提示的配置问题说明

开始只在struts.xml文件中加入以下配置 <constant name="struts.multipart.maxSize" value="10000" /> 在index.jsp文件中加入的 <s:fielderror/>没有显示 只会在控制台打印错误信息: 警告: Request exceeded size limit!org.apache.commons.fileupload.FileUploadBase$SizeLimitExc

vue axios 与 FormData 结合 提交文件 上传文件

---再利用Vue.axios.FormData做上传文件时,遇到一个问题,后台虽然接收到请求,但是将文件类型识别成了字符串,所以,web端一直报500,结果是自己大意了. 1.因为使用了new  FormData来操作表单,并且在测试模拟请求时,从消息头里看到的确实是表单提交[Content-Type: multipart/form-data]. 所以就没有单独在设置. 结果后来加上了这个配置才可以通过了.这里的原理请参照转发大神的原帖. 这个必须设置:Content-Type: multip

JavaWeb 后端 &lt;十四&gt; 文件上传下载

1.文件上传与下载 案例: 注册表单/保存商品等相关模块! --à 注册选择头像 / 商品图片 (数据库:存储图片路径 / 图片保存到服务器中指定的目录) 1.1 文件上传 文件上传,要点: 前台: 1. 提交方式:post 2. 表单中有文件上传的表单项: <input type=”file” /> 3. 指定表单类型: 默认类型:enctype="application/x-www-form-urlencoded" 文件上传类型:enctype =”multipart/