文件上传两种方式和跨服务器上传

文件上传的必要前提

A: form 表单的 enctype 取值必须是:multipart/form-data    
	 (默认值是:application/x-www-form-urlencoded)    
	  enctype:是表单请求正文的类型
B :method 属性取值必须是 Post C 提供一个文件选择域:<input type=”file” /> 

配置放后面:
success.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>文件上传成功</h3>
</body>
</html>

传统文件上传:

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>传统文件上传</h3>
    <form action="user/fileuoload1" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="upload" ></br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

UserController:

@Controller
@RequestMapping("/user")
public class UserController {

    /**
     * 传统文件上传
     * @return
     */
    @RequestMapping("/fileuoload1")
    public String fileuoload1(HttpServletRequest request)  throws Exception{
        System.out.println("文件上传");

        //使用fileupload组件完成文件上传
        //1.上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //2.判断,该路径是否存在
        File file = new File(path);
        if(!file.exists()) {
            //创建文件夹
            file.mkdir();
        }
        System.out.println(path);

        //3.解析request对象,获取上传的文件项
        //磁盘文件项工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解析request
        List<FileItem> items = upload.parseRequest(request);
        //遍历
        for (FileItem item : items) {
            //进行判断,当前item对象是否是上传文件
            if (item.isFormField()) {
                //说明是一个普通表单项
            }else {
                //说明是上传文件项
                //获取上传文件的名称
                String filename = item.getName();
                //把文件名称设置为唯一值,这样上传相同文件就不会覆盖
                String uuid = UUID.randomUUID().toString().replace("-", "");//完成文件上传
                filename = uuid+"_"+filename;
                //完成文件上传
                item.write(new File(path,filename));
                //删除临时文件
                item.delete();
            }
        }
        return "success";
    }
}


MVC方式文件上传:

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>springMVC文件上传</h3>
    <form action="user/fileuoload2" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="upload" ></br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

UserController:

@Controller
@RequestMapping("/user")
public class UserController {
/**
     * springMVC
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileuoload2")                    /*这里名字要和index中文件选择按钮的name一致*/
    public String fileuoload2(HttpServletRequest request, MultipartFile upload)  throws Exception{
        System.out.println("springMVC文件上传");

        //使用fileupload组件完成文件上传
        //1.上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //2.判断,该路径是否存在
        File file = new File(path);
        if(!file.exists()) {
            //创建文件夹
            file.mkdir();
        }
        System.out.println(path);

        //说明是上传文件项
        //获取上传文件的名称
        String filename = upload.getOriginalFilename();
        //把文件加上随机数,防止文件重复 
        String uuid = UUID.randomUUID().toString().replace("-", "");//完成文件上传
        filename = uuid+"_"+filename;
        //完成文件上传
        upload.transferTo(new File(path,filename));

        return "success";
    }
}


跨服务器文件上传:

需要额外创建一个项目用来作为图片服务器来接收文件

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>跨服务器文件上传</h3>
    <form action="user/fileuoload3" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="upload" ></br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

UserController:

@Controller
@RequestMapping("/user")
public class UserController {
/**
     * 跨服务器文件上传
     * @param upload
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileuoload3")                    /*这里名字要和index中文件选择按钮的name一致*/
    public String fileuoload3(MultipartFile upload)  throws Exception{
        System.out.println("跨服务器文件上传");
        //定义上传文件服务器路径
        String path = "http://localhost:9099/uploads/";

        //说明是上传文件项
        //获取上传文件的名称
        String filename = upload.getOriginalFilename();
        //把文件名称设置为唯一值,这样上传相同文件就不会覆盖
        String uuid = UUID.randomUUID().toString().replace("-", "");//完成文件上传
        filename = uuid+"_"+filename;

        //创建客户端的对象
        Client client = Client.create();

        //和图片服务器进行连接
        WebResource webResource = client.resource(path + filename);

        //上传文件
        webResource.put(upload.getBytes());

        return "success";
    }

}

图片服务器无需添加什么 只需配置到Tomcat 注意端口号

springmvc.xml:

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

    <!--开启注解扫描-->
    <context:component-scan base-package="cn.benti"/>

    <!--视图解析器:帮助我们跳转到/WEB-INF/pages/xxx.jsp  -->
    <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="maxInMemorySize" value="10485760" /><!--设置文件大小限制 10M =10*1024*104-->
    </bean>

    <!--开启springMVC框架注解支持-->
    <mvc:annotation-driven />

</beans>

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>cn.benti</groupId>
  <artifactId>springmvc_day02_02</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>springmvc_day02_02 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>

    <!-- 版本锁定 -->
    <spring.version>5.0.2.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>


    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-core</artifactId>
      <version>1.18.1</version>
    </dependency>

    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-client</artifactId>
      <version>1.18.1</version>
    </dependency>


  </dependencies>

  <build>
    <finalName>springmvc_day02_02</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用以下两种方式实现服务器上传下载文件: 1. 使用FTP协议:FTP协议是一种文件传输协议,可以实现服务器上传下载文件。Java中可以使用Apache Commons Net库来实现FTP文件传输。示例代码如下: ``` import org.apache.commons.net.ftp.*; public class FtpExample { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String user = "username"; String pass = "password"; FTPClient client = new FTPClient(); try { client.connect(server, port); client.login(user, pass); client.enterLocalPassiveMode(); String remoteFile = "/path/to/remote/file"; File localFile = new File("/path/to/local/file"); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile)); boolean success = client.retrieveFile(remoteFile, outputStream); outputStream.close(); if (success) { System.out.println("File downloaded successfully."); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (client.isConnected()) { client.logout(); client.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 2. 使用HTTP协议:HTTP协议也可以用于文件传输,可以通过HTTP的POST和GET请求来实现文件上传和下载。Java中可以使用Apache HttpClient库来实现HTTP文件传输。示例代码如下: ``` import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpExample { public static void main(String[] args) { HttpClient httpClient = HttpClients.createDefault(); // 文件上传 HttpPost httpPost = new HttpPost("http://example.com/upload"); FileBody fileBody = new FileBody(new File("/path/to/local/file")); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", fileBody); httpPost.setEntity(builder.build()); try { HttpResponse response = httpClient.execute(httpPost); String result = EntityUtils.toString(response.getEntity()); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } // 文件下载 HttpGet httpGet = new HttpGet("http://example.com/download?file=/path/to/remote/file"); try { HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("/path/to/local/file")); byte[] buffer = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.close(); inputStream.close(); EntityUtils.consume(entity); System.out.println("File downloaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值