SpringMvc实现文件上传与下载

2023-11-17 19:11:41 浏览数 (2)

表单部分代码我就不贴 了,只要注意下表单的enctype="multipart/form-data"这个属性必须加上,表明以二进制的数据格式来传输数据

下面贴出springmvc的Controller代码

代码语言:javascript复制
package com.kailing.controller;


import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
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.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.kailing.po.Upload;
import com.kailing.service.IuploadService;

@Controller
public class UploadController {
	
   private IuploadService uploadService;
   
   @RequestMapping(value={"/","/index.htm"})
   public String index()
   {
	   return "index";
   }
   /**
    * 视频播放页面
    * @param id
    * @param model
    * @return
    */
   @RequestMapping(value="/viedo.htm")
   public String viedo( int id,Model model)
   {
	   model.addAttribute(uploadService.getUpload(id));
	   return "viedo";
   }
   /**
    * 文件列表页面
    * @param model
    * @return
    */
   @RequestMapping(value="/showFiel.htm")
   public String showFile(Model model)
   {
	   List list= uploadService.getAllUpload();
	   model.addAttribute("list", list);
	   return "showFile";
   }
   /**
    * 文件上传
    * @param file
    * @param request
    * @param model
    * @return
    */
   @RequestMapping(value ="/uploads.htm")
   public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {  
       
	   String path = request.getSession().getServletContext().getRealPath("upload");  
      //实际上传文件名
	   String fileName = file.getOriginalFilename();
       //保存至服务器得文件名
       String videoName=UUID.randomUUID().toString() fileName.substring(fileName.lastIndexOf("."), fileName.length());//避免覆盖同名文件
       
        File targetFile = new File(path, videoName);  
       if(!targetFile.exists()){  
           targetFile.mkdirs();  
       }  
       //保存  
       try {  
           file.transferTo(targetFile);  
       } catch (Exception e) {  
           e.printStackTrace();  
       }  
       Upload upload=new Upload();
       upload.setVideoName(videoName);
       upload.setFileName(fileName);
       uploadService.saveUpload(upload);
       return "index";  
   }
   /**
    * 文件下载
    * @param request
    * @param fileName
    * @return
    * @throws IOException
    */
   @RequestMapping("download.htm")  
   public ResponseEntity download(HttpServletRequest request,String videoName,String fileName) throws IOException {  
	   
	   String path = request.getSession().getServletContext().getRealPath("upload");
	 
	   String filepath=path "\"  videoName;
	   
	   File file=new File(filepath);
      
	   HttpHeaders headers = new HttpHeaders();//封装http头部信息  
       
	   headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
       headers.setContentDispositionFormData("attachment",fileName);  //告诉浏览器将要下载的文件名
       
       return new ResponseEntity(FileUtils.readFileToByteArray(file),  
                                         headers, HttpStatus.CREATED);  
   }  
	public void setUploadService(IuploadService uploadService) {
		this.uploadService = uploadService;
	}
}

然后注意下spring的几个配置

代码语言:javascript复制
		        error  

    到此处也基本差不多了,还需要注意的就是,如果你需要异步上传文件,请使用jquery form插件,很实用。

代码语言:javascript复制
	   function tijiao()
	   {
		  	var ajax_option={
		  			success:function(data){
                         alert("上传成功");
		  			}};
		  	$("#form").ajaxSubmit(ajax_option);
	   }

0 人点赞