2010-08-26 61 views
20

我一直在将Spring集成到一个应用程序中,并且必须从表单重做文件上传。 我知道Spring MVC必须提供什么,以及我需要做什么来配置我的控制器以便能够上传文件。我已经阅读了足够的教程来做到这一点,但是这些教程没有解释的是正确/最佳实践方法,以确定如何在实际处理文件后执行/如何完成该操作。下面是一些类似的代码在Spring MVC的文档中发现的处理上传文件的代码可在
Spring MVC File UploadSpring MVC文件上传帮助

发现在下面你的例子中可以看到,他们告诉你什么都做,以获取该文件,但他们只是说做豆与东西

我已经检查了许多教程,他们都似乎让我到这一点,但我真正想知道的是处理该文件的最佳方式。一旦我有一个文件在这一点上,什么是将这个文件保存到服务器上的目录最好的方法是什么?有人可以帮助我吗?由于

public class FileUploadController extends SimpleFormController { 

protected ModelAndView onSubmit(
    HttpServletRequest request, 
    HttpServletResponse response, 
    Object command, 
    BindException errors) throws ServletException, IOException { 

    // cast the bean 
    FileUploadBean bean = (FileUploadBean) command; 

    let's see if there's content there 
    byte[] file = bean.getFile(); 
    if (file == null) { 
     // hmm, that's strange, the user did not upload anything 
    } 

    //do something with the bean 
    return super.onSubmit(request, response, command, errors); 
} 
+1

只需简单地打开输出流并将字节写入流。 FileOutputStram fos = new FileOutputStream(“location/on/server/filename”); fos.write(file); fos.close(); – mhshams 2010-08-26 18:00:48

+0

你确实意识到你正在关注Spring 2.0的文档,对吧?从那以后,事情在春天的世界里发生了很多变化。我强烈建议使用3.0代替,你会发现许多事情更容易,包括文件上传。 – skaffman 2010-08-26 18:48:42

+0

我已经阅读了Spring 3.0的文档以及有关使用多部分表单的文档,并且多部分处理的文档与2.0文档几乎完全相同。 – TheJediCowboy 2010-08-26 20:18:09

回答

20

这是我喜欢做的同时上传。我认为让春天来处理文件保存是最好的方法。 Spring使用它的MultipartFile.transferTo(File dest)函数。

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

import javax.servlet.http.HttpServletResponse; 

import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.bind.annotation.ResponseBody; 
import org.springframework.web.multipart.MultipartFile; 

@Controller 
@RequestMapping("/upload") 
public class UploadController { 

    @ResponseBody 
    @RequestMapping(value = "/save") 
    public String handleUpload(
      @RequestParam(value = "file", required = false) MultipartFile multipartFile, 
      HttpServletResponse httpServletResponse) { 

     String orgName = multipartFile.getOriginalFilename(); 

     String filePath = "/my_uploads/" + orgName; 
     File dest = new File(filePath); 
     try { 
      multipartFile.transferTo(dest); 
     } catch (IllegalStateException e) { 
      e.printStackTrace(); 
      return "File uploaded failed:" + orgName; 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return "File uploaded failed:" + orgName; 
     } 
     return "File uploaded:" + orgName; 
    } 
} 
+0

要获取基本路径,请使用request.getServletContext()。getRealPath(“/”) – Roberto 2016-03-15 23:41:14

+1

@Roberto'getRealPath(“/”)'返回web内容目录。在那里保存文件不是个好主意。当应用程序重新部署时,保存/上传的文件将会丢失。 – 2017-03-14 21:04:09

+0

multipartFile.transferTo(dest);给我IOException。我确信我已经创建了所需的目录。你有什么想法可能是什么原因? – 2017-04-18 14:33:14

2

但什么都不这些教程的讲解是怎样/什么是要做真正处理文件正确/最佳实践方法,一旦你拥有了它

最佳实践取决于你想要做什么。通常我使用一些AOP来后期处理上传的文件。然后你可以使用FileCopyUtils存储你上传的文件

@Autowired 
@Qualifier("commandRepository") 
private AbstractRepository<Command, Integer> commandRepository; 

protected ModelAndView onSubmit(...) throws ServletException, IOException { 
    commandRepository.add(command); 
} 

AOP描述如下

@Aspect 
public class UploadedFileAspect { 

    @After("execution(* br.com.ar.CommandRepository*.add(..))") 
    public void storeUploadedFile(JoinPoint joinPoint) { 
     Command command = (Command) joinPoint.getArgs()[0]; 

     byte[] fileAsByte = command.getFile(); 
     if (fileAsByte != null) { 
      try { 
       FileCopyUtils.copy(fileAsByte, new File("<SET_UP_TARGET_FILE_RIGHT_HERE>")); 
      } catch (IOException e) { 
       /** 
        * log errors 
        */ 
      } 
     } 

    } 

不要忘记启用方面(更新模式到Spring 3.0如果需要的话)放在类路径aspectjrt.jar和aspectjweaver.jar(<SPRING_HOME>/lib中/ AspectJ的)和

<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:aop="http://www.springframework.org/schema/aop" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
          http://www.springframework.org/schema/aop 
          http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> 
    <aop:aspectj-autoproxy /> 
    <bean class="br.com.ar.aop.UploadedFileAspect"/> 
-1

使用下面的控制器类来处理文件上传。

@Controller 
public class FileUploadController { 

    @Autowired 
    private FileUploadService uploadService; 

    @RequestMapping(value = "/fileUploader", method = RequestMethod.GET) 
    public String home() { 
    return "fileUploader"; 
    } 

    @RequestMapping(value = "/upload", method = RequestMethod.POST) 
    public @ResponseBody List<UploadedFile> upload(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException { 

    // Getting uploaded files from the request object 
    Map<String, MultipartFile> fileMap = request.getFileMap(); 

    // Maintain a list to send back the files info. to the client side 
    List<UploadedFile> uploadedFiles = new ArrayList<UploadedFile>(); 

    // Iterate through the map 
    for (MultipartFile multipartFile : fileMap.values()) { 

     // Save the file to local disk 
     saveFileToLocalDisk(multipartFile); 

     UploadedFile fileInfo = getUploadedFileInfo(multipartFile); 

     // Save the file info to database 
     fileInfo = saveFileToDatabase(fileInfo); 

     // adding the file info to the list 
     uploadedFiles.add(fileInfo); 
    } 

    return uploadedFiles; 
    } 

    @RequestMapping(value = {"/listFiles"}) 
    public String listBooks(Map<String, Object> map) { 

    map.put("fileList", uploadService.listFiles()); 

    return "listFiles"; 
    } 

    @RequestMapping(value = "/getdata/{fileId}", method = RequestMethod.GET) 
    public void getFile(HttpServletResponse response, @PathVariable Long fileId) { 

    UploadedFile dataFile = uploadService.getFile(fileId); 

    File file = new File(dataFile.getLocation(), dataFile.getName()); 

    try { 
     response.setContentType(dataFile.getType()); 
     response.setHeader("Content-disposition", "attachment; filename=\"" + dataFile.getName() + "\""); 

     FileCopyUtils.copy(FileUtils.readFileToByteArray(file), response.getOutputStream()); 


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


    private void saveFileToLocalDisk(MultipartFile multipartFile) throws IOException, FileNotFoundException { 

    String outputFileName = getOutputFilename(multipartFile); 

    FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(outputFileName)); 
    } 

    private UploadedFile saveFileToDatabase(UploadedFile uploadedFile) { 
    return uploadService.saveFile(uploadedFile); 
    } 

    private String getOutputFilename(MultipartFile multipartFile) { 
    return getDestinationLocation() + multipartFile.getOriginalFilename(); 
    } 

    private UploadedFile getUploadedFileInfo(MultipartFile multipartFile) throws IOException { 

    UploadedFile fileInfo = new UploadedFile(); 
    fileInfo.setName(multipartFile.getOriginalFilename()); 
    fileInfo.setSize(multipartFile.getSize()); 
    fileInfo.setType(multipartFile.getContentType()); 
    fileInfo.setLocation(getDestinationLocation()); 

    return fileInfo; 
    } 

    private String getDestinationLocation() { 
    return "Drive:/uploaded-files/"; 
    } 
} 
+0

UploadedFile未定义。 – MuffinMan 2015-11-06 21:39:39