springmvc 上傳文件隨記筆記實例給初學者

利用springMVC實現文件及圖片上傳功能,它主要是有MultipartResolver來實現的,咱們經過配置這個MultipartResolver,能夠實現咱們的圖片上傳的方法。web

1.配置以前準備,這裏咱們須要用到兩個包spring

commons-fileupload和commons-ioapache

2.我這裏在myeclipse環境引入相應jar包json

3.在xxx-servlet.xml裏面輸入咱們的bean,multipartResolver數組

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
        p:defaultEncoding="utf-8" 
        p:maxUploadSize="52428800"
        p:uploadTempDir="upload/temp" />tomcat

4.建立一個接收圖片的方法uploadimg,參數是MultipartFile類型的,還有HttpServletRequest。具體實現能夠看代碼。服務器

publicString uploadimg(MultipartFileavata,HttpServletRequestrequest){app

Stringfileurl="";dom

{eclipse

if(avata.isEmpty()){

System.out.println("沒法找到文件");

return"";

}else{

System.out.println("文件長度:"+avata.getSize());

System.out.println("文件類型:"+avata.getContentType());

System.out.println("文件名稱:"+avata.getName());

System.out.println("文件原名:"+avata.getOriginalFilename());

System.out.println("========================================");

StringrealPath=request.getSession().getServletContext().getRealPath("/WEB-INF/yeehot");

FiletargetFile=newFile(realPath);

if(!targetFile.exists()){

targetFile.mkdirs();

}

System.out.println(realPath);

inti=avata.getOriginalFilename().lastIndexOf(".");//返回最後一個點的位置

Stringextension=avata.getOriginalFilename().substring(i+1);//取出擴展名

Stringfilename=UUID.randomUUID().toString()+"."+extension;

fileurl=filename;

try{

avata.transferTo(newFile(realPath,filename));

}catch(IllegalStateExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}catch(IOExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

returnfileurl;

}

}

}

5.建立一個controller.而且調用剛纔上傳圖片的方法。最後打印圖片的路徑

@Controller

publicclassUploafAvataController{

@ResponseBody

@RequestMapping(value="/uploadavata")

publicStringupload(@RequestParam(value="file",required=false)MultipartFilefile,HttpServletRequestrequest,ModelMapmodel){

Stringpath=uploadimg(file,request);

returnrequest.getContextPath()+"/yeehot/"+path;

}

}

6.建立上傳圖片的jsp,注意一點就是enctype,這裏一點要知名上傳的類型是"multipart/form-data",

<body>

<formaction="uploadavata"method="post"enctype="multipart/form-data">

選擇文件:<inputtype="file"name="file">

<inputtype="submit"value="提交">

</form>

</body>

7.測試上傳結果,輸入咱們的項目路徑:

http://192.168.3.114:8080/Yeehot-Program-King/upload.jsp

點擊提交後能夠看到以下路徑說明圖片上傳成功

咱們能夠從tomcat服務器的

/apache-tomcat-7.0.69/webapps/Yeehot-Program-King/WEB-INF/yeehot目錄下找到咱們的圖片

對於上傳多圖片的方法。

咱們可使用MultipartFile[]數組。咱們把原來的代碼改爲以下

一、上傳圖片的方法,這裏我輸出爲json數組。

publicStringuploadimgs(MultipartFile[]avatas,HttpServletRequestrequest){

Stringfileurl="";

JSONArrayimgArray=newJSONArray();

for(MultipartFileavata:avatas){

if(avata.isEmpty()){

System.out.println("沒法找到文件");

}else{

System.out.println("文件長度:"+avata.getSize());

System.out.println("文件類型:"+avata.getContentType());

System.out.println("文件名稱:"+avata.getName());

System.out.println("文件原名:"+avata.getOriginalFilename());

System.out.println("========================================");

StringrealPath=request.getSession().getServletContext().getRealPath("/WEB-INF/yeehot");

FiletargetFile=newFile(realPath);

if(!targetFile.exists()){

targetFile.mkdirs();

}

System.out.println(realPath);

inti=avata.getOriginalFilename().lastIndexOf(".");//返回最後一個點的位置

Stringextension=avata.getOriginalFilename().substring(i+1);//取出擴展名

Stringfilename=UUID.randomUUID().toString()+"."+extension;

fileurl=filename;

JSONObjectjsonObject=newJSONObject();

jsonObject.put("img",fileurl);

imgArray.add(jsonObject);

try{

avata.transferTo(newFile(realPath,filename));

}catch(IllegalStateExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}catch(IOExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

}

}

returnimgArray.toString();

}

二、在controller編寫接受的方法

@ResponseBody

@RequestMapping(value="/uploadavatamulti")

publicStringuploadmul(@RequestParam(value="files",required=false)MultipartFile[]file,HttpServletRequestrequest,ModelMapmodel){

//Stringpath=uploadimg(file,request);

Stringpath=uploadimgs(file,request);

returnpath;

}

三、編寫上傳多文件的JSP。注意這裏file的name="files"要和controller的一致。

<formaction="uploadavatamulti"method="post"enctype="multipart/form-data">

選擇文件:<inputtype="file"name="files"><br>

選擇文件:<inputtype="file"name="files"><br>

選擇文件:<inputtype="file"name="files"><br>

<inputtype="submit"value="提交">

</form>

四、測試多文件上傳

http://192.168.3.114:8080/Yeehot-Program-King/uploadmul.jsp

注意,可能會出現org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException:therequestwasrejectedbecauseitssize(249681)exceedstheconfiguredmaximum(204800)

這是因爲咱們剛剛限制文件上傳的大小。這裏超過了咱們的文件最大值,這裏是全部文件的大小。解決辦法,咱們能夠增長文件上傳的大小。我這裏就用2048000.

<!--文件上傳表單的視圖解析器-->

<beanid="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!--oneofthepropertiesavailable;themaximumfilesizeinbytes-->

<propertyname="maxUploadSize"value="2048000"/>

</bean>

若是上傳成功會返回以下的數據。

[

{

"img":"10edd053-52f0-4a14-a8e0-93cbcd8f60bd.png"

},

{

"img":"7547f880-e23f-40e6-b8bc-f4f9b30d6edf.png"

},

{

"img":"7c29cab1-b2e4-406e-871b-800b4f26698b.png"

}

]

相關文章
相關標籤/搜索