spring实现简单的文件上传

上传文件的jsp代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>

<form action="${pageContext.request.contextPath}/uploadImg.form" method="post" enctype="multipart/form-data">
    <input type="file" name="upload"/>
    <input type="submit" name="上传">
</form>
</body>
</html>

后台的controller路径

其中request.getserveletContext是为了获取到当前程序的根目录,getRealPath是为了拿到对应路径下的文件夹

package com.ittest.controller;

import jdk.internal.cmm.SystemResourcePressureImpl;
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 javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.UUID;
@Controller
public class testController {
    @RequestMapping(value = "/uploadImg")
    public void findDataByConditions(HttpServletRequest request, HttpServletResponse response, MultipartFile upload) throws Exception {
        // 上传图片 的 原名称
        String oldName = upload.getOriginalFilename();
        String newName = null;
        //解决文件重名问题
        //其中使用uuid来实现重命名,h后面hi截取文件的类型
        String finalFileName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
        //获取文件的根路径+
        String path = request.getServletContext().getRealPath("photo")+File.separator+finalFileName;
        System.out.println("文件 的路径是"+path);
        upload.transferTo(new File(path));
        System.out.print(oldName);

    }

}

实现效果:

这样通过uuid来实现出防止重复上传的效果

 

源代码:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值