1. 程式人生 > >java檔案上傳|ssm框架前臺檔案上傳後臺接收原理

java檔案上傳|ssm框架前臺檔案上傳後臺接收原理

第一步:

首先是jsp的form部分程式碼:

<form action="up" encType="multipart/form-data" method="post">
    <label>選擇檔案</label>
    <input id="fileId" name="file" type="file"/>
    <input type="submit" value="提交"/>    
</form>

第二步:

@RequestMapping("/up")
    public String uploadImg(HttpServletRequest request) throws IllegalStateException, IOException
    {
        //拼接檔案儲存的目錄,這個路徑是系統專案的路徑
        String temp=Thread.currentThread().getContextClassLoader().getResource("").getPath(); 
        int num=temp.indexOf(".metadata");
        String path=temp.substring(1,num).replace('/', '\\')+request.getContextPath().replaceAll("/",     "")+"\\WebContent\\images\\";
        
        //上傳檔案,異地上傳檔案是以檔案流的形式上傳的
        List<String> list = FileUtil.upLoad(request, path);//FileUtil是檔案接收上傳的工具類
        request.setAttribute("path", list.get(0));
        return "upok"; 
        
    }

第三部工具類:

public class FileUtil
{
    
    public static List<String> upLoad(HttpServletRequest request,String path)
    {
        
        List<String> list = new ArrayList<String> ();    //存放結果
        //1、將當前上下文初始化給CommonMutipartResolver
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //2、檢查Form中encType是否為multipart/form-data
        if(multipartResolver.isMultipart(request))
        {
            //將request轉為MultipartHttpServletRequest
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            //獲取迭代器遍歷multipartRequest裡的檔名
            Iterator<String> iter = multipartRequest.getFileNames();
            while(iter.hasNext())
            {
                //獲取檔案並向下遍歷
                MultipartFile file = multipartRequest.getFile(iter.next().toString());
                if(file != null)
                {
                    //獲取檔案型別,即字尾名
                    String str = file.getOriginalFilename();
                    String suffix = str.substring(str.lastIndexOf("."));
                    
                    //用 當前日期+UUID作為檔名避免重名
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                    String dateStr = sdf.format(new Date()).replaceAll("-", "");
                    String name = dateStr +UUID.randomUUID().toString().replaceAll("-", "");
                    
                    //拼接檔案絕對路徑
                    String filePath = path + name + suffix;
                    try
                    {
                        file.transferTo(new File(filePath));//將檔案寫入到指定的路徑當中
                    } catch (IllegalStateException | IOException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    list.add(filePath);//將上傳的檔案路徑放在list集合中,在控制層可以拿到已經上傳的檔案路徑
                }
            }
        }
        return list;
        
    }

}