程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> springmvc-spring mvc做上傳圖片,文件小於10k就不生成臨時文件了

springmvc-spring mvc做上傳圖片,文件小於10k就不生成臨時文件了

編輯:編程綜合問答
spring mvc做上傳圖片,文件小於10k就不生成臨時文件了

這是spring-mvc.xml中的

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartRe     solver">
    <property name="defaultEncoding" value="UTF-8" />
    <!-- 指定所上傳文件的總大小不能超過2000KB。注意maxUploadSize屬性的限制     不是針對單個文件,而是所有文件的容量之和 -->
    <property name="maxUploadSize" value="2048000" />
    <property name="maxInMemorySize" value="10240" />  
</bean>

下面是方法:

@RequestMapping(value="uploadFile.do",method={RequestMethod.GET,RequestMethod.POST})
    public String ajaxUpload(ModelMap mm,HttpSession ses,HttpServletRequest req
            ) throws Exception {
        try {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;     
            // 獲得文件:
                MultipartFile upload = multipartRequest.getFile("upload");  
            String newFileName = new Date().getTime() + "_" + SesHelper.getSimUser(ses).getManageUser().getMuId()
                    + getExtention(upload.getOriginalFilename());

            CommonsMultipartFile cf= (CommonsMultipartFile)upload;
                DiskFileItem fi = (DiskFileItem)cf.getFileItem();
                File targetFile = fi.getStoreLocation();

            if(ArrayUtils.indexOf(imageExtentions, getExtention(upload.getOriginalFilename()).substring(1))!=-1){
                **RemoteFileUtil.copyImage(targetFile, newFileName);**
            }else{
                throw new BaseException("請確定是圖片文件");
            }
            handleSuc(mm);
            mm.put("msg", imgServerName+newFileName);
        } catch (Exception e) {
            handleErr(mm , e);
        }
        return JSON_COM;
        }

上面的調這個方法

    public static synchronized void copyImage(File src, String filename) {
        try {
            **copy(src, filename);**
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("請檢查服務器:" + serverIps[0] + ":" + serverPorts[0] + "是否連接通暢");
        }
    }

上面的調這個方法

private static synchronized void copy(File src, String filename)
            throws UnknownHostException, IOException {
        for (int i = 0; i < serverIps.length; i++) {
            Socket client = new Socket(serverIps[i], Integer
                    .parseInt(serverPorts[i]));
            OutputStream os = client.getOutputStream();
            os.write((filename + ";").getBytes());
            byte[] byteBuffer = new byte[1];
            FileInputStream fos = new FileInputStream(src);
            BufferedInputStream bis = new BufferedInputStream(fos);
            System.out.println(filename);
            **while (bis.read(byteBuffer) != -1) {
                os.write(byteBuffer);
            }**
            os.flush();
            bis.close();
            fos.close();
            os.close();
            client.close();
            System.out.println(client.getLocalAddress());
        }
    }
下面是頁面
    <script type="text/javascript">
    axUpload=true;
    var fileName = "";
    function ajaxuploadsubmit() {
        var index = layer.load();
        $('#uploadForm').ajaxSubmit({
            url:'${siteUrl}/file/uploadFile.do',
            type:'post',
            dataType: 'json',
            success:function (data){
                if(data.code == "S"){
                    layer.close(index);
                    layer.msg("文件上傳成功,上傳文件的文件名為"+data.msg, {icon: 1});
                    fileName = data.msg;
                    closeAndOpenSuc();
                }else{
                    layer.close(index);
                    layer.msg(data.msg, {icon: 2});
                }

            }
        });
    }

    function closeAndOpenSuc() {
        layer.close(uploadObj.imgLayerId);
        $('#'+uploadObj.imgInputId).val(fileName);
        $('#'+uploadObj.imgShowId).attr("src",fileName);
    }

    function closeAndOpen() {
        layer.close(uploadObj.imgLayerId);
    }
</script>

<div class="modal-content">
    <div class="modal-body">
        <form id="uploadForm" class="form-horizontal" role="form" enctype="multipart/form-data">
        <div class="padd">
        <div class="form quick-post">
            <div class="form-group">
                <label class="control-label col-lg-2" style="width:100px;padding-top:5px;">選擇文件</label>
                <div class="col-lg-6">
                    <input id="upload" type="file" size="30" height="20px" name="upload">
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-lg-2" style="width:100px;padding-top:5px;">&nbsp;</label>
                <div class="col-lg-6">
                    <input type="button" name="button" value="上傳文件" class="btn btn-success" onclick="ajaxuploadsubmit()" />
                </div>
            </div>      
        </div>
        </div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" onclick="closeAndOpen()">關閉</button>
    </div>
</div>

報錯信息
while (bis.read(byteBuffer) != -1) {
os.write(byteBuffer);
}
中會報錯

java.io.FileNotFoundException: C:\apache-tomcat-7.0.61\work\Catalina\localhost\FishManage\upload_de2e4204_56e7_4b34_adce_163e38e29654_00000003.tmp (系統找不到指定的文件。)

最佳回答:


已解決,問題出在配置文件上

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8" />
        <!-- 指定所上傳文件的總大小不能超過2000KB。注意maxUploadSize屬性的限制不是針對單個文件,而是所有文件的容量之和 -->
        <property name="maxUploadSize" value="2048000" />
        <!-- 設置在文件上傳時允許寫到內存中的最大值,以字節為單位計算,默認是10240 -->
        <!-- 但是經實驗,上傳文件大小若小於此參數,則不會生成臨時文件,很尴尬,故改為2048 -->
        <property name="maxInMemorySize" value="2048" />  

    </bean>
    ```
    maxInMemorySize這個參數得改的小一點
canhanyue
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved