SpringMVC文件上传

1.导入所需要的jar包
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
2.配置springmvc.xml


<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8">property>
<property name="maxInMemorySize" value="102400">property>
bean>

上传jsp代码:

"${pageContext.request.contextPath }/testUpload" enctype="multipart/form-data" method="post" > 选择要上传的文件:type="file" name="photo" value="上传文件" >
描述:type="text" name="describe"> type="submit" value="上传">

controller代码

//上传练习
    @RequestMapping(value="/testUpload",method=RequestMethod.POST)
    public String testUpload(HttpServletRequest request,@RequestParam(value="describe")String describe,@RequestParam(value="photo")CommonsMultipartFile file){
        System.out.println(describe);
        System.out.println(file.getOriginalFilename());
        ServletContext scontext=request.getServletContext();
        String path=scontext.getRealPath("/pages");
        File f=new File(path);
        if(!f.exists()){
            f.mkdir();
        }
        OutputStream out;
        InputStream in;
        //uuid_name.jpg
        String prefix = UUID.randomUUID().toString();
        prefix = prefix.replace("-","");
        String fileName = prefix+"_"+file.getOriginalFilename();
        System.out.println(fileName);

        try {
            out = new FileOutputStream(new File(path+"\\"+fileName));
            System.out.println(new File(path+"\\"+fileName).exists());
            in = file.getInputStream();
            IOUtils.copy(in, out);
            out.close();
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "redirect:index.jsp";
    }

练习中的问题:
1.xml文件中的id一定要有
2.if(!f.exists()){
f.mkdir();
}判断要有
3.保证文件名不同
String prefix = UUID.randomUUID().toString();
prefix = prefix.replace(“-“,”“);
String fileName = prefix+”_”+file.getOriginalFilename();
System.out.println(fileName);

你可能感兴趣的:(springmvc,文件上传)