Spring Uploading Files

1,在servlet-dispatcher.xml中添加代码

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



也可以根据需求添加相关属性
< property   name = "maxUploadSize"   value = "2097152" > </ property >    

2,添加依赖jar文件

		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>

3、编写uploadController

    @RequestMapping(value="/upload",method=RequestMethod.POST)  
    public String processUpload(@RequestParam("name") String name, 
    		@RequestParam("file") MultipartFile file) throws IOException {  
      	log.info("File '" + file.getOriginalFilename() + "' uploaded successfully");
      	if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                
                
                
                return "You successfully uploaded " + name + "!";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }  

4、使用RestClient测试上传


后台提示:

[2015-08-18 11/:36/:12]INFO  com.kaishuhezi.api.hardware.log.controller.LogController(line/:40) -File '78a0f7dcjw1e1bvyuzt1jj.jpg' uploaded successfully


转载于:https://www.cnblogs.com/duyinqiang/p/5696578.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值