springboot练习-文件上传

//上传文件页面
<!DOCTYPE html> <html> <head> <title>uploadimg.html</title> <meta name="keywords" content="keyword1,keyword2,keyword3"></meta> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="/js/test.js" type="text/javascript"></script> </head> <body> <form enctype="multipart/form-data" method="post" action="/upload"> 文件:<input type="file" name="head_img"/> 姓名:<input type="text" name="name"/> <input type="submit" value="上传"/> </form> </body> </html>//简单处理上传业package wei.com.demo2.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;



import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import wei.com.demo2.bean.JsonData;

/**
 * 功能描述:文件测试
 */
@Controller
public class UploadController {
    
    @RequestMapping(value = "/api/v1/gopage")  
    public Object index() {
        return "index";
    }
    
    private static final String filePath = "C:/Users/chen1/Desktop/java/";
   
    
    @RequestMapping(value = "upload")
    @ResponseBody
    public JsonData upload(@RequestParam("head_img") MultipartFile file,HttpServletRequest request) {
          
        //file.isEmpty(); 判断图片是否为空
        //file.getSize(); 图片大小进行判断 
        String name = request.getParameter("name");
        System.out.println("用户名:"+name);
            
        // 获取文件名
        String fileName = file.getOriginalFilename();            
        System.out.println("上传的文件名为:" + fileName);
            
        // 获取文件的后缀名,比如图片的jpeg,png
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为:" + suffixName);
            
        // 文件上传后的路径
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("转换后的名称:"+fileName);
            
        File dest = new File(filePath + fileName);
           
        try {
            file.transferTo(dest);  
            return new JsonData(0, fileName);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return  new JsonData(-1, "fail to save ", null);
        }
}

猜你喜欢

转载自www.cnblogs.com/big-cut-cat/p/9508809.html