码迷,mamicode.com
首页 > 编程语言 > 详细

spring 上传文件

时间:2017-07-18 00:02:11      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:catch   --   commons   mon   puts   服务   pat   share   成功   

1、配置文件部分

在spring的配置文件中加入下面代码

<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"/>

2、用到的jar包

commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
 
3、代码部分--上传到本地文件夹
public class UploadController {

    //设置文件的路径
    File filePath = new File("D:/workspace-letter");
    
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    //可以成功调取
    public String upload(@RequestParam  MultipartFile file) throws IOException {
        
        //获取文件原始名称
        String filename = file.getOriginalFilename();
        //获取文件扩展名
        String fileExtension = filename.substring(filename.lastIndexOf("."));
        //img  文件名前缀
        File tempFile = File.createTempFile("img", fileExtension,filePath);

        try{
            InputStream in = file.getInputStream();
            OutputStream out = new FileOutputStream(tempFile);
            IOUtils.copy(in, out);
        }catch(Exception e){
            e.printStackTrace();
        }
        return filename;
    }
}

4、上传到服务器

 

@Controller
public class UploadController {
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam  MultipartFile file, HttpServletRequest request) throws IOException {
                //设置服务器的上传路径
        File filePath = new File("//sharedata//p4");
        
        String filename = file.getOriginalFilename();
        String fileExtension = filename.substring(filename.lastIndexOf("."));
        File tempFile = File.createTempFile("LETTER", fileExtension,filePath);

        try {
            InputStream in = file.getInputStream();
            OutputStream out = new FileOutputStream(tempFile);
            IOUtils.copy(in, out);
        } catch (Exception e) { 
            e.printStackTrace();
        }
        return filePath.getPath() + "/" + filename;
    }

}    

 

 

 

spring 上传文件

标签:catch   --   commons   mon   puts   服务   pat   share   成功   

原文地址:http://www.cnblogs.com/guoyinli/p/7197680.html

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