ssm项目中常用的上传文件

时间:2024-04-30 04:07:24
  • 在项目中,上传文件一般是必不可少的,所以今天学到新的上传方式,就干脆将学习过的上传方式记录一下

    一、表单直接上传图片

  • 表单头要设置
    <form action="" method="post" enctype="multipart/form-data">
  • 元素
    <input type="file" name="dwfile" >
  • 后端代码

    @RequestMapping(value="addDownload",method=RequestMethod.POST)
    public String addDownload(HttpServletRequest request,Model model,download download)throws Exception{
    log.info("上传文件");
    try{
    String fileName = download.getDwfile().getOriginalFilename();
    System.out.println("原始文件名:" + fileName);
    // 新文件名
    //String newFileName = UUID.randomUUID() + fileName;
    // 获得项目的路径
    ServletContext sc = request.getSession().getServletContext();
    // 上传位置
    String path = sc.getRealPath("/upload") + "/"; // 设定文件保存的目录
    System.out.println(path);
    File f = new File(path);
    if (!f.exists())
    f.mkdirs();
    if (!download.getDwfile().isEmpty()) {
    FileOutputStream fos = new FileOutputStream(path + fileName);
    InputStream in = download.getDwfile().getInputStream();
    int b = 0;
    while ((b = in.read()) != -1) {
    fos.write(b);
    }
    fos.close();
    in.close();
    }
    download.setDwFile(fileName);
    downloadService.insertSelective(download); }catch(Exception e){
    System.out.println(e);
    }
    return "redirect:showDownload";
    }

    二、使用ajax上传

  • ssm项目中常用的上传文件
  • 1.通过jquery的插件jquery.form.js

  • jsp页面代码
    <form id="form111" name="form111" action="${path }/brand/addBrand.do" method="post" enctype="multipart/form-data">
    <input type='file' size='27' id='imgsFile' name='imgsFile' class="file" onchange='submitUpload()' />

  • js代码

    <script type="text/javascript" src="<c:url value='/{system}/res/js/jquery.form.js'/>"></script> 
    function submitUpload(){
    var option = { url:"{path}/upload/uploadPic.do",//如果不指定url那么就使用使用提交表单的url,如果指定就使用当前的url
    dataType:"text",
    success:function(responseText){
    var jsonObj = .parseJSON(responseText);("#imgsImgSrc").attr("src", jsonObj.realPath);
    $("#imgs").val(jsonObj.relativePath); },
    error:function(){
    alert("系统错误");
    }
    };
    $("#form111").ajaxSubmit(option); }
  • 后端接收
    @RequestMapping("/uploadPic.do")
    public void uploadPic(HttpServletRequest request, Writer out) throws IOException{
    //把request转换成复杂request
    MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
    //获得文件
    Map<String, MultipartFile> map = mr.getFileMap();
    Set<String> set = map.keySet();
    Iterator<String> it = set.iterator();
    String fileInputName = it.next();
    MultipartFile mf = map.get(fileInputName);
    //获得文件的字节数组
    byte [] bs = mf.getBytes();
    String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
    Random random = new Random();
    for(int i = 0; i < 3; i++){
    fileName = fileName + random.nextInt(10);
    } String oriFileName = mf.getOriginalFilename();
    //获得文件的后缀
    String suffix = oriFileName.substring(oriFileName.lastIndexOf("."));
    //获得上传文件的绝对路径(上传和展示)
    String realPath = ECPSUtils.readProp("file_path")+"/upload/"+fileName+suffix;
    //获得相对路径(存储在数据库)
    String relativePath = "/upload/"+fileName+suffix;
    //创建jersy的客户端
    Client client = Client.create();
    //创建web资源对象
    WebResource wr = client.resource(realPath);
    //上传
    wr.put(bs);
    JSONObject jo = new JSONObject();
    jo.accumulate("realPath", realPath);
    jo.accumulate("relativePath", relativePath);
    String result = jo.toString();
    out.write(result);
    }

    2.使用FormData对象

  • 这种还没有使用过,以后研究

    ajax基本使用json数据