文件上传下载代码

本文介绍了一个基于SpringMVC的文件上传和下载功能实现,通过MultipartFile处理文件上传,利用自定义工具类完成文件的保存与读取。同时,提供了文件下载的API,支持通过HTTP请求直接下载文件。
  • 上传
 @Value("${DOWNLOAD_PATH}")
 private String path;
	
@RequestMapping(value = "/uploadFile",method= RequestMethod.POST)
	@ResponseBody
	public void handleFormUpload(@RequestParam("file") MultipartFile file) {
		AjaxResponseBody ajaxResponseBody = new AjaxResponseBody();
		List<String> namePathlist=new ArrayList<String>();
		try {
			if (file != null && file.getOriginalFilename() != "") {
				//获取到真正的文件的名称
				String realName = file.getOriginalFilename();
				namePathlist.add(realName);
				InputStream in = file.getInputStream();
				String allPath=FileUtil.uploadFile(in, path,realName);
				namePathlist.add(allPath);
			}
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		
		ajaxResponseBody.setSuccess(true);
		ajaxResponseBody.setData(namePathlist);
		ReturnUtil.success(request, response, ajaxResponseBody);
	}
  • 下载
@RequestMapping(value = "/downloadFile")
	@ResponseBody
	public void adduser(HttpServletRequest request,HttpServletResponse response, String path,String realName) throws Exception {
		FileUtil.downloadFile(path, realName, request, response);
	}
  • 工具类
package comframe.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileUtil {
	
	
	public static String uploadFile(InputStream is,String savePath,String realName) throws IOException{
		File file = new File(savePath);
		System.out.println(file.getCanonicalPath());
		if (!file.exists() && !file.isDirectory()) {
            System.out.println(savePath+"目录不存在,需要创建");
            //创建目录
            file.mkdir();
        }
		String filename = UUIDUtil.genStrByRandom(false);
		//获取文件的后缀
		String substring = realName.substring(realName.indexOf("."));
		
		String allPath = savePath + "/" + filename+substring;
		
		try {
			FileOutputStream out = new FileOutputStream(allPath);
			
			 byte buffer[] = new byte[1024];
			 
			 int len = 0;
			 
			 while((len=is.read(buffer))>0){
			     //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
			     out.write(buffer, 0, len);
			 }
			 
			 is.close();
			 //关闭输出流
			 out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
         
         return allPath;
	}
	
	
	
	public static void downloadFile(String path,String realName,HttpServletRequest request, HttpServletResponse response) {

		try {
			String fileName = realName.toString(); 
			// 文件的默认保存名
			File file = new File(path);
			System.out.println(file.getCanonicalPath());
	        InputStream inStream = new BufferedInputStream(new FileInputStream(path));
	        
	        byte[] buffer = new byte[inStream.available()];
	        inStream.read(buffer);
	        
            
	        response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
	        
	        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	        
	        toClient.write(buffer);
            toClient.flush();
            toClient.close();
            
	        if (inStream != null) {
	            inStream.close();
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值