java中檔案的上傳(簡單的操作)

來源:互聯網
上載者:User

標籤:rac   fileutil   原因   mem   base64   filename   array   blog   new   

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

<!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架構

後端的代碼如下:

@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的設定檔中加上一段配置。如下:

 

Required CommonsMultipartFile parameter ‘file‘ is not present
報這個錯的時候可以在項目中加一個配置,原因是位元組數太大

<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圖片,我的部落格裡面會有單獨的說明。

 

java中檔案的上傳(簡單的操作)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.