1. 程式人生 > >解決使用Spring Boot、Multipartfile上傳檔案路徑錯誤問題

解決使用Spring Boot、Multipartfile上傳檔案路徑錯誤問題

Spring 4 MVC Single and Multiple File Upload Example with Tomcat

August 09, 2014 In this page we will learn how to upload a file in Spring 4 MVC. We are presenting the demo for single and multiple file upload. We are using XML less configurations. MultipartConfigElement Bean needs to be configured for file upload. In controller, method argument should be MultipartFile class for uploading the file. The JSP form, enctype must be set for multipart form data. Check the demo now.

Software Used

To run the file upload demo in Spring 4, get ready with below software. 
1. JDK 7 
2. Eclipse 
3. Tomcat 7 
4. Gradle 2.0 for Spring Boot

Project Structure in Eclipse

For better understanding, get the file location in eclipse how to put our classes and JSPs. Spring 4 MVC  Single and Multiple File Upload  Example  with Tomcat

Controller Class: Use of MultipartFile

In our example we are presenting demo for single and multiple file upload. So we have created two different methods for uploading the file. In single upload, the method should have the parameter as below with other parameters.
@RequestParam("file")MultipartFile file 
And for multiple file upload , the parameter should be as below
@RequestParam
("file")MultipartFile[] file
Get the name of file from MultipartFile object and save it to your desired location. Find the controller. 
FileUploadController.java
package com.concretepage;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;@ControllerpublicclassFileUploadController{@RequestMapping(value="/singleUpload")publicString singleUpload(){return"singleUpload";}@RequestMapping(value="/singleSave", method=RequestMethod.POST )public@ResponseBodyString singleSave(@RequestParam("file")MultipartFile file,@RequestParam("desc")String desc ){System.out.println("File Description:"+desc);String fileName =null;if(!file.isEmpty()){try{
                fileName = file.getOriginalFilename();byte[] bytes = file.getBytes();BufferedOutputStream buffStream =newBufferedOutputStream(newFileOutputStream(newFile("F:/cp/"+ fileName)));
                buffStream.write(bytes);
                buffStream.close();return"You have successfully uploaded "+ fileName;}catch(Exception e){return"You failed to upload "+ fileName +": "+ e.getMessage();}}else{return"Unable to upload. File is empty.";}}@RequestMapping(value="/multipleUpload")publicString multiUpload(){return"multipleUpload";}@RequestMapping(value="/multipleSave", method=RequestMethod.POST )public@ResponseBodyString multipleSave(@RequestParam("file")MultipartFile[] files){String fileName =null;String msg ="";if(files !=null&& files.length >0){for(int i =0;i< files.length; i++){try{
	                fileName = files[i].getOriginalFilename();byte[] bytes = files[i].getBytes();BufferedOutputStream buffStream =newBufferedOutputStream(newFileOutputStream(newFile("F:/cp/"+ fileName)));
	                buffStream.write(bytes);
	                buffStream.close();
	                msg +="You have successfully uploaded "+ fileName +"<br/>";}catch(Exception e){return"You failed to upload "+ fileName +": "+ e.getMessage()+"<br/>";}}return msg;}else{return"Unable to upload. File is empty.";}}}

Configuration Class: Use of MultipartConfigElement Bean

In the configuration class, we need to use bean for MultipartConfigElement and UrlBasedViewResolver. MultipartConfigElement supports the file upload where we can set max file size, max request size etc. MultipartConfigElement needs to be configured with Dispatcher servlet using WebApplicationInitializer . UrlBasedViewResolver defines the JSP location and file extension pattern of output. 
AppConfig.java
package com.concretepage;import javax.servlet.MultipartConfigElement;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 org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.view.JstlView;import org.springframework.web.servlet.view.UrlBasedViewResolver;@Configuration@ComponentScan@EnableWebMvc@EnableAutoConfigurationpublicclassAppConfig{@BeanpublicMultipartConfigElement multipartConfigElement(){MultipartConfigFactory factory =newMultipartConfigFactory();
        factory.setMaxFileSize("128KB");
        factory.setMaxRequestSize("128KB");return factory.createMultipartConfig();}@BeanpublicUrlBasedViewResolver setupViewResolver(){UrlBasedViewResolver resolver =newUrlBasedViewResolver();  
        resolver.setPrefix("/views/");  
        resolver.setSuffix(".jsp");  
        resolver.setViewClass(JstlView.class);return resolver;}}

WebApplicationInitializer Class: Use of Dynamic.setMultipartConfig()

WebApplicationInitializer is used when our application is not using web.xml. This supports all functionality which web.xml does. To supports file upload our dispatcher must be set for multipart config. 
WebAppInitializer.java
package com.concretepage;import javax.servlet.MultipartConfigElement;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRegistration.Dynamic;import org.springframework.web.WebApplicationInitializer;import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;import org.springframework.web.servlet.DispatcherServlet;publicclassWebAppInitializerimplementsWebApplicationInitializer{publicvoid onStartup(ServletContext servletContext)throwsServletException{AnnotationConfigWebApplicationContext ctx =newAnnotationConfigWebApplicationContext();  
        ctx.register(AppConfig.class);  
        ctx.setServletContext(servletContext); 
        ctx.refresh();Dynamicdynamic= servletContext.addServlet("dispatcher",newDispatcherServlet(ctx));dynamic.addMapping("/");dynamic.setLoadOnStartup(1);dynamic.setMultipartConfig(ctx.getBean(MultipartConfigElement.class));}}

View: Use of enctype="multipart/form-data" and type="file"

The JSPs are being used as views. To support file upload, form must be set with enctype for multipart form data and there should a file input text. We have two JSP. Find the JSP for single file upload. 
singleUpload.jsp
<html><body><h1>Single File Upload</h1><formmethod="post"enctype="multipart/form-data"action="singleSave">
		Upload File: <inputtype="file"name="file"><br/><br/>
		Description: <inputtype="text"name="desc"/><br/><br/><inputtype="submit"value="Upload"></form></body></html>
Find the JSP for multiple file Upload. We need to take care that each input type of file type must have same name, so that it could be accessed as an array. 
multipleUpload.jsp
<html><body><h1> Multiple File Upload </h1><formmethod="post"enctype="multipart/form-data"action="multipleSave">
		Upload File 1: <inputtype="file"name="file"><br/>
		Upload File 2: <inputtype="file"name="file"><br/>
		Upload File 3: <inputtype="file"name="file"><br/>
		Upload File 4: <inputtype="file"name="file"><br/><br/><br/><inputtype="submit"value="Upload"></form></body></html>

Spring Boot Jar Dependency using Gradle

Find the gradle script for JAR dependency and creating WAR file of the project. Spring boot web and security are being used. 
build.gradle
apply plugin:'java'
apply plugin:'eclipse'
apply plugin:'war'
archivesBaseName ='CP'
repositories {
    mavenCentral()}
dependencies {
   compile 'org.springframework.boot:spring-boot-starter-web:1.1.4.RELEASE'
   compile 'org.springframework.boot:spring-boot-starter-security:1.1.4.RELEASE'
   compile 'javax.servlet:jstl:1.2'
   compile 'commons-fileupload:commons-fileupload:1.3.1'}

Deploy in Tomcat 7 To Check Output

Go to build directory in your project and inside lib you will get WAR file. Deploy in in tomcat and test. In our demo we are using tomcat 7. 
Single File Upload Output
For single upload use the URL as http://localhost:8080/CP/singleUpload Spring 4 MVC  Single and Multiple File Upload  Example  with Tomcat Spring 4 MVC  Single and Multiple File Upload  Example  with Tomcat
Multiple File Upload Output
For multiple file upload use the URL as http://localhost:8080/CP/multipleUpload Spring 4 MVC  Single and Multiple File Upload  Example  with Tomcat Spring 4 MVC  Single and Multiple File Upload  Example  with Tomcat

Download Source Code

相關推薦

解決使用Spring BootMultipartfile檔案路徑錯誤問題

Spring 4 MVC Single and Multiple File Upload Example with Tomcat August 09, 2014 In this page we will learn how to upload a file in Spring 4 MVC. We are

解決 Spring MVC 使用 CommonsMultipartResolver 檔案亂碼

使用SpringMVC配置MultipartResolver來上傳中文檔名的檔案時,出現中文亂碼的問題,解決方案: @Bean public MultipartResolver multipartResolver(){ CommonsMultipartResolver multipa

spring boot 下 ajax 檔案

jsp: <div class="modelFile fl"> <form method="POST" enctype="multipart/form-data" id="fileUploadForm"> <inpu

Spring boot(16) spring boot 線上故障 檔案出錯:org.springframework.web.multipart.MultipartException: Could

上線後,過了一段時間上傳檔案的時候 出現錯誤 org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception

Spring Boot 與 Kotlin 檔案

如果我們做一個小型的web站,而且剛好選擇的kotlin 和Spring Boot技術棧,那麼上傳檔案的必不可少了,當然,如果你做一箇中大型的web站,那建議你使用雲端儲存,能省不少事情。 這篇文章就介紹怎麼使用kotlin 和Spring Boot上傳檔案

spring boot 整合oss 圖片檔案

前排宣告: 本文章 整合修改自https://blog.csdn.net/hcjsjqjssm/article/details/80977735 部落格 一是自己以後回顧,二希望可以幫助到使用此功能的同學,假使幫助到了你,可以點個贊,留個言,如果有不成功的 也可以留言 一起解決下

[Spring Boot] Spring Boot MultipartFile檔案

Spring Boot 上傳檔案程式碼 Spring Boot 使用MultipartFile來完成檔案上傳 @ResponseBody @RequestMapping(value = "/put") public Boolean putFi

spring mvc MultipartFile 文件錯誤解決

文件 上傳 ces port not in servle resolv spa AR org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.s

Spring MultipartFile 檔案檔案getInputStream無法獲取輸入流問題

MultipartFile file; file能獲取表單上傳檔案基本資訊(檔名和字尾名) InputStream input = file.getInputStream(); 但無法獲取Stream,原因為Spring配置問題 <bean id="multipar

Spring Boot文件示例(Ajax和REST)

模型 custom rop null nds con and 程序 docs 本文介紹如何使用Ajax請求在Spring Boot Web應用程序(REST結構)中上傳文件。 本文中使用的工具: Spring Boot 1.4.3.RELEASE Spring 4.3.5

spring boot 文件 文件過大 FileUploadBase$SizeLimitExceed

prop post class exce 1.4 part tip exc log application.properties中加入 multipart.maxFileSizemultipart.maxRequestSize Spring Boot 1.3.x或者之前 m

spring boot 2.X文件限制大小

code 限制 1.4 大小 http class and sin span Spring Boot 1.3.x multipart.maxFileSize multipart.maxRequestSize Spring Boot 1.4.x and 1.5.x s

SpringMVC使用MultipartFile檔案

1. MultipartFile基本介紹 MultipartFile是springmvc官方提供的一個比較完善的檔案上傳元件,MultipartFile是一個組織介面它的實現類有 org.springframework.web.multipart.commons.CommonsMultipartFi

MultipartFile檔案始終是NULL

html程式碼: <form action="http://127.0.0.1:8080/pic/myupload" method="POST" enctype="multipart/form-data">     <input typ

基於Spring Boot實現圖片/加水印一把梭操作

文章共 537字,閱讀大約需要 2分鐘 ! 概述 很多網站的圖片為了版權考慮都加有水印,尤其是那些圖片類網站。自己正好最近和圖片打交道比較多,因此就探索了一番基於 Spring Boot這把利器來實現從 圖片上傳 → 圖片加水印 的一把梭操作! 注: 本文首發於 M

JavaWeb——使用Vue+Spring Boot實現Excel

寫在最前 在上期教程中我們介紹了讀寫Excel與使用Selenium的入門方法,本期將介紹通過Vue+Spring Boot實現在WebApp中上傳Excel匯入測試指令碼的功能。使用前後端分離的技術是因為這樣便於後續功能的迭代,在本文中我們只涉及一個簡單的前端介面及一個簡單的後臺服務。 執行結果展示與原

製作七牛-spring-boot-starter並中央倉庫

說明 最近使用七牛雲的時候突然想自己製作一個springboot-starter版本,畢竟可以把ak,sk等等直接寫在application.yml裡實在是很好用啊。於是自己製作了qiniu-spring-boot-starter 0.1 RELEASE版(目前版本有簡單上

spring boot 圖片的與顯示

首先描述一下問題,spring boot 使用的是內嵌的tomcat, 所以不清楚檔案上傳到哪裡去了, 而且spring boot 把靜態的檔案全部在啟動的時候都會載入到classpath的目錄下的,所以上傳的檔案不知相對於應用目錄在哪,也不知怎麼寫訪問路徑合適,對於新手

spring boot + vue新增圖片功能

餘近日開發spring boot +vue的後臺管理專案,涉及到檔案上傳功能,使用之前專案的檔案上傳模組,一直有問題。遂經過兩天的百度,加個人理解,最終解決了基本的檔案上傳功能。     首先,html頁面: <!--form中是要加這個enctype的-->

hadoop錯誤解決辦法:-------HDFS檔案儲存錯誤或速度很慢

出現症狀: 2018-11-22 11:28:12,711 WARN hdfs.DataStreamer: Abandoning BP-2142139802-10.20.2.1-1536240602405:blk_1073765062_24289 2018-11-22 11:28:12,71