1. 程式人生 > >springmvc框架上傳檔案操作

springmvc框架上傳檔案操作

 前端頁面為,通過form表單提交

<form method="post" action="uploadFile" enctype="multipart/form-data">
        <input type="file" name="myFile">
        <input type="submit" value="上傳">
    </form>

1,首先要將上傳檔案所需要的jar包拷貝過來(第一個為檔案上傳jar包,第二個IO流的jar包)

2.第二步:在springmvc-servlet.xml檔案中配置檔案上傳解析器(property還有更多設定,在此僅舉一個例子)

<!--檔案上傳解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 設定上傳檔案的最大尺寸為1MB -->
        <property name="maxUploadSize">
            <value>1048576</value>
        </property>
    </bean>

3.後端接收,將檔案儲存在指定資料夾中

@Controller
public class FileDemo {
    //檔案上傳
    @RequestMapping("/uploadFile")
    public String uploadFile(MultipartFile myFile){
        System.out.println(myFile.getOriginalFilename());
        //將檔案存放在指定資料夾
        String filename = myFile.getOriginalFilename();
        File filepath = new File("D:/images/"+filename);
        InputStream in = null;
        try {
            in = myFile.getInputStream();
            FileUtils.copyInputStreamToFile(in , filepath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "index";
    }