您的足迹:首页 > JAVA >springmvc 实现简单上传和下载

springmvc 实现简单上传和下载

spring提供了简单的上传和下载机制,只需简单几句代码就能够实现上传和下载

下载


package com.youngpioneers.memory.web;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping
public class DownloadController {
	 @RequestMapping("download")    
	 public ResponseEntity<byte[]> download() throws IOException {    
	        String path="C:\\Users\\Administrator\\Desktop\\apache.txt";  
	        File file=new File(path);  
	        HttpHeaders headers = new HttpHeaders();    
	        String fileName=new String("apache2.txt".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
	        headers.setContentDispositionFormData("attachment", fileName);   
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
	        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                          headers, HttpStatus.CREATED);    
	    }    
}



上传


@ResponseBody
	@RequestMapping(value = "/uploadLogo")
	public String uploadLogo(
			@RequestParam(value = "logo", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		String path = request.getSession().getServletContext()
				.getRealPath("/upload");// 绝对路径
		String fileName = Calendar.getInstance().getTimeInMillis()
				+ file.getOriginalFilename();// 文件名
		File targetFile = new File(path + "/" + fileName);
		// 保存
		try {
			file.transferTo(targetFile);// 储存文件

		} catch (Exception e) {
			e.printStackTrace();
		}

		// model.addAttribute("fileUrl",
		// request.getContextPath()+"/upload/"+fileName);
		return "upload/" + fileName;
	}


上传还需要配置上传文件解析器


<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 配置最大上传文件的大小 -->
		<property name="maxUploadSize" value="20000000" />
	</bean>
	<aop:config proxy-target-class="true"></aop:config>
	<bean
		class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager" />
	</bean>


本博客所有文章如无特别注明均为原创。作者:小天复制或转载请以超链接形式注明转自 钟天才的博客
原文地址《springmvc 实现简单上传和下载

相关推荐

网友评论(0)