SpringMVC文件上傳

SpringMVC和Struts2的區別
共同點:
1.都是web層框架,都是基於MVC模型編寫
2.底層都離不開原始ServletAPI
3.處理請求的機制都是一個核心控制器html

區別:
1.SpringMVC的入口是Servlet,而Struts2是Filter
2.SpringMVC是基於方法設計的,而Struts2是基於類,Struts2每次執行都會建立一個動做類。因此SpringMVC會稍微比Struts2快些
3.SpringMVC使用更加簡潔,同時還支持JSR303,處理ajax請求更方便java

搭建SpringMVC工程步驟web

最後一步最重要,我踩過多少坑才知道ajax

fix完以後,tomcat服務器就能夠跑起來了,不須要敲一行代碼,也不須要配置代碼spring

 

下面是正題apache

效果圖api

index.jspspring-mvc

<%-- Created by IntelliJ IDEA. User: wanglei Date: 2019/7/27 Time: 14:59 To change this template use File | Settings | File Templates. --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
</head>
<body>
<h3>傳統文件上傳</h3>

<form action="user/fileupload1" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上傳"/>
</form>

<h3>SpringMVC文件上傳</h3>

<form action="user/fileupload2" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上傳"/>
</form>

<h3>跨服務器文件上傳</h3>

<form action="user/fileupload3" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上傳"/>
</form>
</body>
</html>

dispatcher-servlet.xmltomcat

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--開啓註解掃描-->
    <context:component-scan base-package="com.jinke.controller"/>

    <!--視圖解析器對象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--配置文件解析器對象-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"/>
    </bean>

    <!--開啓SpringMVC框架註解的支持-->
    <mvc:annotation-driven/>
</beans>

UploadController.java服務器

import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.List; import java.util.UUID; @Controller @RequestMapping("/user") public class UploadController { /** * 跨服務器上傳方式 * * @return * @throws Exception */ @RequestMapping("/fileupload3") public String fileupload3(MultipartFile upload) throws Exception { System.out.println("跨服務器文件上傳..."); //定義上傳服務器路徑
        String path = "http://localhost:9090/Fileserver/uploads/"; //上傳文件項
        String filename = upload.getOriginalFilename(); String uuid = UUID.randomUUID().toString().replace("-", ""); String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1); //建立客戶端對象
        Client client = Client.create(); //和圖片服務器進行鏈接
        WebResource webResource = client.resource(path + saveName); //上傳文件
 webResource.put(upload.getBytes()); return "success"; } /** * SpringMVC上傳方式 * * @param request * @return * @throws Exception */ @RequestMapping("/fileupload2") public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception { System.out.println("springmvc文件上傳..."); //上傳的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/"); //判斷該路徑是否存在
        File file = new File(path); if (!file.exists()) { file.mkdirs(); } //上傳文件項
        String filename = upload.getOriginalFilename(); String uuid = UUID.randomUUID().toString().replace("-", ""); String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1); upload.transferTo(new File(path, saveName)); return "success"; } /** * 傳統上傳方式 * * @param request * @return * @throws Exception */ @RequestMapping("/fileupload1") public String fileupload1(HttpServletRequest request) throws Exception { System.out.println("文件上傳..."); //上傳的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/"); //判斷該路徑是否存在
        File file = new File(path); if (!file.exists()) { file.mkdirs(); } //解析request對象
        DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); //遍歷
        for (FileItem item : items) { if (item.isFormField()) { //普通表單向
            } else { //上傳文件項
                String filename = item.getName(); String uuid = UUID.randomUUID().toString().replace("-", ""); String saveName = uuid + "_" + filename.substring(filename.lastIndexOf(File.separator) + 1); item.write(new File(path, saveName)); //刪除臨時文件
 item.delete(); } } return "success"; } }

須要注意的是,若是配置了CommonsMultipartResolver,傳統上傳方式就走不通了,由於提早過濾掉了

若是從應用服務器上傳文件到文件服務器,保存路徑要寫對

歡迎關注個人微信公衆號:安卓圈

相關文章
相關標籤/搜索