java中文件的上傳(簡單的操做)

首先文件的上傳只能使用表單提交的方式,其中須要幾個jar包  commons-io-1.3.2.jar,commons-fileupload-1.2.1jar,頁面的代碼以下:javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript"></script>
</head>
<body>
</head>
<body>
</div>
<form action="pp" enctype ="multipart/form-data" method="post">
<input type="file" name="image">
<input type="submit" value="提交">
</form>
</body>
</html>

開發的框架使用的是springmvc框架html

後端的代碼以下:java

@RequestMapping(value="pp") public String reg5(@RequestParam("image") CommonsMultipartFile[] files,HttpServletRequest request){ String path = request.getContextPath(); String str =null; for(int i = 0;i<files.length;i++){ if(!files[i].isEmpty()){ str = request.getSession().getServletContext().getRealPath("/")+"fileUpload\\temp"+ new Date().getTime() + files[i].getOriginalFilename(); System.out.println(str); int pre = (int) System.currentTimeMillis(); String filename=files[i].getOriginalFilename(); try {
//這個工具類我就不提供了,就是把文件寫入本地文件。 FileUtils.writeByteArrayToFile(
new File(str,filename), files[i].getBytes(),true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return "success"; }

在springmvc框架中傳遞的文件很大,可能會傳不過去,你能夠在 spring的配置文件中加上一段配置。以下:web

 

Required CommonsMultipartFile parameter 'file' is not present
報這個錯的時候能夠在項目中加一個配置,緣由是字節數太大spring

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600" />
        <property name="maxInMemorySize" value="4096" />
    </bean>

 

 

 

其實這個文件要是一個圖片,你要是想存在數據庫,能夠把它生成一個base64的圖片,只是一段字符串。。。。直接就能夠存儲。數據庫

拿出來放在image標籤的src裏面就能夠展現圖片了,可是像素可能會有影響,你能夠在生成時設置一下。後端

如何生成base64圖片,個人博客裏面會有單獨的說明。mvc

相關文章
相關標籤/搜索