2010-08-26 35 views
20

Tôi đã tích hợp lò xo vào ứng dụng và phải làm lại tệp tải lên từ biểu mẫu. Tôi biết những gì Spring MVC cung cấp và những gì tôi cần làm để cấu hình bộ điều khiển của mình để có thể tải lên tệp. Tôi đã đọc đủ hướng dẫn để có thể làm điều này, nhưng những gì không có trong những hướng dẫn này giải thích là phương pháp thực hành tốt nhất/chính xác về cách/những gì sẽ được thực hiện để thực sự xử lý các tập tin khi bạn có nó. Dưới đây là một số mã tương tự để mã được tìm thấy trên Spring MVC Docs về xử lý tập tin tải lên có thể được tìm thấy tại
Spring MVC File UploadTrợ giúp tải lên tệp Spring MVC

Trong ví dụ bên dưới, bạn có thể thấy rằng họ chỉ cho bạn tất cả những gì phải làm để có được các tập tin, nhưng họ chỉ cần nói Làm điều gì đó với đậu

Tôi đã kiểm tra nhiều hướng dẫn và tất cả dường như đưa tôi đến thời điểm này, nhưng điều tôi thực sự muốn biết là cách tốt nhất để xử lý tệp. Khi tôi có một tệp tại thời điểm này, cách tốt nhất để lưu tệp này vào thư mục trên máy chủ là gì? Ai đó có thể giúp tôi với điều này? Cảm ơn

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

chỉ cần mở đầu ra và ghi byte vào luồng. FileOutputStram fos = new FileOutputStream ("vị trí/trên/máy chủ/tên tệp"); fos.write (tệp); fos.close(); – mhshams

+0

Bạn nhận ra rằng bạn đang theo dõi tài liệu cho Spring 2.0, phải không? Mọi thứ đã di chuyển rất nhiều trong thế giới mùa xuân kể từ đó. Tôi khuyên bạn nên sử dụng 3.0 thay vào đó, bạn sẽ tìm thấy nhiều thứ dễ dàng hơn nhiều, bao gồm cả việc tải lên tệp. – skaffman

+0

Tôi đã đọc tài liệu cho Spring 3.0 về việc sử dụng các biểu mẫu nhiều phần và tài liệu về xử lý nhiều phần gần giống với tài liệu 2.0. – TheJediCowboy

Trả lời

20

Đây là những gì tôi thích khi thực hiện cập nhật. Tôi nghĩ rằng để cho mùa xuân để xử lý các tập tin tiết kiệm, là cách tốt nhất. Mùa xuân thực hiện nó với chức năng MultipartFile.transferTo(File dest) của nó.

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

Để lấy đường dẫn cơ bản, hãy sử dụng request.getServletContext(). GetRealPath ("/") – Roberto

+1

@Roberto 'getRealPath ("/")' trả về dir nội dung web. Ý tưởng không tốt để lưu tệp trong đó. Khi ứng dụng redeploys, các tập tin đã lưu/tải lên sẽ bị mất. –

+0

multipartFile.transferTo (dest); cho tôi IOException. Tôi chắc chắn rằng tôi đã tạo ra các thư mục cần thiết. Bạn có bất kỳ ý tưởng về lý do có thể là gì? –

2

nhưng những gì không ai trong số những hướng dẫn giải thích là đúng/phương pháp thực hành tốt nhất về cách/gì là phải làm để thực sự xử lý các tập tin một khi bạn có nó

Các thực hành tốt nhất phụ thuộc vào những gì bạn đang cố gắng làm. Thông thường tôi sử dụng một số AOP để post-proccessing các tập tin được tải lên. Sau đó, bạn có thể sử dụng FileCopyUtils để lưu trữ tập tin tải lên của bạn

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

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

AOP được mô tả như sau

@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 
        */ 
      } 
     } 

    } 

Đừng quên cho phép khía cạnh (update schema để mùa xuân 3,0 nếu cần) Đặt trên aspectjrt.jar classpath và aspectjweaver.jar (<SPRING_HOME>/lib/AspectJ) và

<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

Sử dụng lớp điều khiển bên dưới để xử lý tải lên tệp.

@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 không được xác định. – MuffinMan

Các vấn đề liên quan