Java中附件上傳

來源:互聯網
上載者:User

標籤:一個   comm   ram   https   方式   multi   change   resolve   value   

1、因為上傳檔案會使用到MultipartHttpServletRequest對象,我們需要在Springmvc設定檔中配置一個解析器

    <!--為了使用到spring為我們提供的,MultipartHttpServletRequest對象,我們需要配置一個解析器 -->       <!-- 而且對於Bean組件要想正常運行,必須配置一個id屬性 -->       <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">         <!-- 請求編碼方式 -->         <property name="defaultEncoding" value="UTF-8"/>         <!-- 上傳檔案大小 -->         <property name="maxUploadSize" value="10000000"/>         <!-- 緩衝區大小 -->         <property name="maxInMemorySize" value="1024"/>                </bean>

2、前端jsp代碼

<div>     <span>上傳附件:</span><input type="file" id="accessory1"  name="accessory1" onchange="checkFile(this)" />     <font size="2" color="red">注意:上傳檔案大小不能超過10M</font>
</div>
      //上傳檔案校正         function checkFile(file){             var flag = getFilesize(file);             if(!flag){                 var fileInput = $("#accessory1");  
          //驗證不通過,清空input框 fileInput.replaceWith(fileInput.clone()); } } var fileSize = 0; //檔案大小預設為0 function getFilesize(file) { /*(1)判斷檔案尾碼類型*/ var strs = new Array(); //定義一數組 var pic1 = $(file).val(); //擷取input框的值,檔案路徑 strs = pic1.split(‘.‘); //分成數組儲存 var suffix = strs[strs.length - 1]; //擷取檔案尾碼 if (suffix != ‘pdf‘ && suffix != ‘docx‘ && suffix != ‘doc‘&& suffix != ‘txt‘) { alert("僅能上傳副檔名為pdf、docx、doc、text的檔案!"); return false; } /*(2)擷取檔案大小,以Kb為單位*/ fileSize = file.files[0].size / 1024; if (fileSize > 10000) { alert("您選擇的檔案太大,請選擇小於10M的檔案!"); return false; } return true; }
           // 表單提交時執行的方法                var form = new FormData();                form.append("accessory1", $(‘#accessory1‘)[0].files[0]);

//後端請求處理
   @RequestMapping(value="/addGg",method=RequestMethod.POST) @ResponseBody public boolean addGg(MultipartFile accessory1){//發布公告的同時是否有附件上傳 if (accessory1 != null ) {
       logger.info("<--帶有附件公告發布開始-->"); InputStream is = null; try { is = accessory1.getInputStream(); byte[] b = new byte[is.available()]; is.read(b); jjkjGggl.setAccContent(b); } catch (IOException e) { logger.info("<--附件讀取異常!-->:"+e); throw new RuntimeException("附件讀取異常!"); } finally{ try { is.close(); } catch (IOException e) { logger.info("<--附件讀取釋放資源異常!-->:"+e); throw new RuntimeException("附件讀取釋放資源異常!"); } } }return false; }

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.