springMVC 單個文件上傳

  1. web端jspjavascript

    1.首先有一個包含type="file"類型的表單 ,我的將表單的id="form",具體以下java

    <form class="form-horizontal" id="form" method="post" enctype="multipart/form-data"  role="form">jquery

                    <div class="modal-header">web

                       <button type="button" class="close" data-dismiss="modal" aria-label="Close" ><span aria-hidden="true">&times;</span></button>ajax

                        <h4 class="modal-title" id="editModalLabel">發佈系統公告</h4>spring

                    </div>json

                    <div class="modal-body">mvc

                                <div class="form-group">app

                                    <label class="col-md-2 control-label" for="title">標題</label>jsp

                                   <div class="col-md-8">

                                       <input class="form-control" id="title" name="title" type="text" placeholder="請輸入公告標題"/>

                                       <input type="hidden" name="id" id="id" />

                                    </div>

                                </div>

                               <div class="form-group">

                                    <label class="col-md-2 control-label" for="file">附件</label>

                                    <div class="col-md-8">

                                        <input class="form-control" name="myFile"  id="file" type="file" />

                                  </div>

                                </div>

                                <div class="form-group">

                                   <label class="col-md-2 control-label" >公告內容</label>

                                 <div class="col-md-8">

                                        <textarea class="form-control" name="message" id="message" rows="10" placeholder="請輸入公告內容"></textarea>

                                    </div>

                                </div>

                        

                    </div>

                    <div class="modal-footer">

                        <button type="submit" class="btn btn-success">保存</button>

                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>

                    </div>

                    </form>

注:由於是帶有文件的表單,因此 enctype="multipart/form-data" 必須有。由於我的項目業務是須要ajax提交表單,可是ajax不能提交文件信息,故,我用了jquery-form.js中的ajaxSubmit方法提交此表單數據,具體以下:

 2.web端的js

/*加載表單方法*/

    function submitForm() {

        //點擊保存按鈕時

       $('#form').submit(function() {

      $("#form").ajaxSubmit({

      dataType:'json',

      type: "post",

               url: url,

          success: function (data) {

         成功時執行方法

      },   error: function () {

          失敗時執行方法

           }

         });

       

        return false;

        });

    }

注:submitForm()這個方法請在頁面加載完成時執行這個方法即,具體以下:

<script type="text/javascript">

    $(function () {

   submitForm() 

});

</script>

經過以上方法就能夠順利將文件傳到後臺了。下面是後臺java代碼處理的具體實現。

(1)controller層

@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)

    @Operate("發佈系統公告信息")

    public ResponseEntity<?> create(Notice notice,@RequestParam("myFile") MultipartFile file) {

        //保存任務

    try {

    noticeService.insert(notice, file);

    } catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace(); 

}

        return new ResponseEntity(notice, HttpStatus.OK);

    }

(2)service層

public void insert(Notice notice, MultipartFile file) throws Exception{

if (notice.getId()!=null) {

Notice n=dao.get(notice.getId());

if (n!=null) {

//更改文件

uploadFile(notice, file);

//文件不爲空

if (file!=null) {

deleteFile(n);

}

}

}else {

dao.insert(notice);

//更改文件

uploadFile(notice, file);

}

   dao.update(notice);

}

public void uploadFile(Notice notice, MultipartFile file) throws Exception{

if (file!=null) {

String fileType=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);

String filePath=Constant.FILE_SYS_NOTICE+notice.getId();

String fileName=System.currentTimeMillis()+"."+fileType;

notice.setFilePath((filePath+"/"+fileName).replace("\\", "/"));

notice.setFileName(fileName);

notice.setFileTrueName(file.getOriginalFilename());

FileUploadUtil.uploadFile(file,filePath ,fileName);

}

}

public void deleteFile(Notice notice){

File delFile=new File(Constant.FILE_PATH_ROOT_TUREPATH.replaceAll("\\\\","/")+notice.getFilePath());

delFile.delete();

}

public void delete(Integer id){

Notice notice=dao.get(id);

if (notice!=null) {

deleteFile(notice);

}

dao.delete(id);

}


/*FileUploadUtil.uploadFile類以下**/

/**

 * 上傳文件的工具類

 * @author  may

 *

 */

public class FileUploadUtil {

    public static void  uploadFile(MultipartFile file,String savePath, String fileName) 

    throws IOException  {

    String path = Constant.FILE_PATH_ROOT_TUREPATH + savePath;

    File upload = null;

       try {

        if (file!=null) {

            upload = new File(path);

                // 若是指定的路徑沒有就建立

                if (!upload.exists()) {

                upload.mkdirs();

                }

        }

        File file2=new File(upload, fileName);

        file.transferTo(file2);

} catch (Exception e) {

// TODO Auto-generated catch block

throw new IOException(e);

}

}



以上關於springmvc的上傳附件的增刪改後臺,及前臺提交附件基本已經完成了,本人菜鳥,寫出來是但願本身可以記住及爲本身之後想用到的時候能夠直接使用,有bug和缺漏的地方但願各位多多包涵。

相關文章
相關標籤/搜索