SpringMVC的文件上传

SpringMVC-文件上传

单服务器代码实现

springmvc.xml中配置文件解析器对象

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 最大文件大小 -->
    <property name="maxUploadSize" value="10485760"/>
</bean>

注意:其id值只能为multipartResolve,不能将其改变,否则无效。


Controller中编写业务代码,在形参中添加MultipartFile对象,将其命名为请求参数名

@RequestMapping("/mvcUpload")
//添加MultipartFile对象
public String mvcUpload(HttpServletRequest request, MultipartFile file) throws IOException {
    //设置保存路径
    String path = request.getSession().getServletContext().getRealPath("/upload/");
    File files = new File(path);
    if (!files.exists()){
        files.mkdirs();
    }

    //获取文件名
    String name = file.getOriginalFilename();
    String uuid = UUID.randomUUID().toString().replace("-", "");
    //保存文件
    file.transferTo(new File(path, uuid+"_"+name));

    return "success";
}


多服务器代码实现

实现一个应用服务器向文件服务器上传文件

prom.xml中导入坐标

<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>

Controller中实现业务代码

/**
 * 多服务器上传
 * @param file 文件
 * @return 成功页面
 * @throws IOException 异常
 */
@RequestMapping("/serverUpload")
public String serverUpload(MultipartFile file) throws IOException {
    //定义上传文件服务器路径
    String path = "http://localhost:8080/upload/";
    //获取文件名
    String name = file.getOriginalFilename();
    String uuid = UUID.randomUUID().toString().replace("-", "");

    //完成跨服务器上传
    //1.创建客户端的对象
    Client client = Client.create();
    //2.与文件服务器进行连接
    WebResource resource = client.resource(path+name);
    //3.上传文件
    resource.put(file.getBytes());

    return "success";
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值