転送:Spring bootファイルアップロード

7260 ワード

回転:
http://www.cnblogs.com/rollenholt/p/3693087.html
1.Mavenのwebプロジェクトを作成し、pom.xmlファイルを配置し、依存を追加する:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.0.2.RELEASE</version>
</dependency>
2.webappディレクトリのindex.jspファイルにフォームを入力します。

<html>
<body>
<form method="POST" enctype="multipart/form-data"
      action="/upload">
    File to upload: <input type="file" name="file"><br /> Name: <input
        type="text" name="name"><br /> <br /> <input type="submit"
                                                     value="Upload"> Press here to upload the file!
</form>
</body>
</html>
このフォームは私達がシミュレーションしたアップロードページです。
3.このフォームを扱うControllerを作成する:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
 
@Controller
public class FileUploadController {
 
    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }
 
    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + " into " + name + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }
 
}
4.そしてアップロードされたファイルに対して制限をして、同時にメールの作成方法でこのウェブを起動します。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.MultiPartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
import javax.servlet.MultipartConfigElement;
 
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
 
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultiPartConfigFactory factory = new MultiPartConfigFactory();
        factory.setMaxFileSize("128KB");
        factory.setMaxRequestSize("128KB");
        return factory.createMultipartConfig();
    }
 
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
5.そして訪問http://localhost:8080/uploadページが見えます。
上の例は単一ファイルアップロードの機能を実現しています。今ファイルの大量アップロードの機能を実現するには、上のコードを簡単に修正すればいいです。紙幅の問題を考慮して、下には上と違ったコードを貼るだけです。貼っていない説明は上と同じです。
1.batch Upload.jspファイルを追加する
	
<html>
<body>
<form method="POST" enctype="multipart/form-data"
      action="/batch/upload">
    File to upload: <input type="file" name="file"><br />
    File to upload: <input type="file" name="file"><br />
    <input type="submit" value="Upload"> Press here to upload the file!
</form>
</body>
</html>
2.Batch FileUploadController.javaファイルを追加します。
	
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
 
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
 
/**
 * Created by wenchao.ren on 2014/4/26.
 */
 
@Controller
public class BatchFileUploadController {
 
    @RequestMapping(value="/batch/upload", method= RequestMethod.POST)
    public @ResponseBody
    String handleFileUpload(HttpServletRequest request){
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
        for (int i =0; i< files.size(); ++i) {
            MultipartFile file = files.get(i);
            String name = file.getName();
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    BufferedOutputStream stream =
                            new BufferedOutputStream(new FileOutputStream(new File(name + i)));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    return "You failed to upload " + name + " => " + e.getMessage();
                }
            } else {
                return "You failed to upload " + name + " because the file was empty.";
            }
        }
        return "upload successful";
    }
}
このように簡単な量でファイルをアップロードする機能はokです。簡単ですか?
上のコードはただデモンストレーションのためですので、コードのスタイルは勝手な方式をとっています。
参考資料:
1.MultiiprtResoloverはファイルアップロード機能も実現できます。参考記事:
http://mylfd.iteye.com/blog/1893648