Java SpringMVC文件几种上传,附带fromdata文件加参数上传

首先mvc配置

    
    
    
     

     

1、设置上传xml


     
	     
	     
     

2、上传.java

		@ResponseBody
		@CrossOrigin(origins = "*", maxAge = 3600)
		@RequestMapping(value="/upload",method=RequestMethod.POST)
	    public String upload(HttpServletRequest req) throws Exception{
			
	        MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
	        req.setCharacterEncoding("UTF-8");
	        MultipartFile file = mreq.getFile("img0");
	        String fileName = file.getOriginalFilename();
	        String q_title=new String(fileName.getBytes("ISO8859-1"),"UTF-8");
	        System.out.println(q_title);
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");   
	        System.out.println(req.getSession().getServletContext().getRealPath("/"));
	        System.out.println(fileName);
	        FileOutputStream fos = new FileOutputStream("D:\\FFOutput\\"+sdf.format(new Date())+fileName);
	        fos.write(file.getBytes());
	        fos.flush();
	        fos.close();
	        
	        return "hello";
	    }


另外几种

1、

//将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
           //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();

2、

CommonsMultipartFile file
File newFile=new File(path);
        //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
        file.transferTo(newFile);

3、

CommonsMultipartFile file
//获取输出流
            OutputStream os=new FileOutputStream("E:/"+new Date().getTime()+file.getOriginalFilename());
            //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            InputStream is=file.getInputStream();
            byte[] bts = new byte[1024];
            //一个一个字节的读取并写入
            while(is.read(bts)!=-1)
            {
                os.write(bts);
            }
           os.flush();
           os.close();
           is.close();
          
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

4、表单与文件一同上传

HttpServletRequest request;

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

MultipartFile file = multipartRequest.getFile("file");

String id = multipartRequest.getParameter("id");

String fileName = file.getOriginalFilename(); 

html:


你可能感兴趣的:(java)