angularjs + springmvc 上傳和下載

來源:互聯網
上載者:User

標籤:maxsize   enc   人文   contains   logs   global   char   ann   www.   

jsp:

<form ng-submit="uploadFile()" class="form-horizontal" enctype="multipart/form-data">                <input type="file" name="file" ng-model="document.fileInput" id="file" onchange="document.getElementById(‘filepath‘).value=this.value;" />                <input  name=‘filepath‘ id=‘filepath‘>                <button class="btn btn-primary" type="submit">                    Submit                </button>            </form>

js:

$scope.uploadFile=function(){            var formData=new FormData();            formData.append("file",file.files[0]);            $http.post(VX.CONFIG.rootPath+‘/uploadFile‘, formData, {                transformRequest: function(data, headersGetterFunction) {                    return data;                },                headers: { ‘Content-Type‘: undefined }            }).success(function(data, status) {                console.log(data);                console.log("Success ... " + status);            }).error(function(data, status) {                console.log("Error ... " + status);                console.log(data);            });            };

java:

package com.nirvanainfo.salesleads.api.controller.common;import com.nirvanainfo.salesleads.api.utils.Global;import com.nirvanainfo.salesleads.api.utils.ImageHandleUtill;import com.nirvanainfo.salesleads.api.utils.ResultBean;import com.nirvanainfo.salesleads.api.utils.ResultPageBean;import com.nirvanainfo.salesleads.service.convert.CsvUtil;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileItemFactory;import org.apache.commons.fileupload.FileUpload;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.json.simple.JSONObject;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.PrintWriter;import java.text.NumberFormat;import java.text.SimpleDateFormat;import java.util.*;/** * Created by Choice on 2016/4/25. */@Controller@RequestMapping("uploadFile")public class UploadFileController extends BaseController{    private static Log log = LogFactory.getLog(UploadFileController.class);    @RequestMapping("")    public @ResponseBody Object UploadFile(@RequestParam(value="file", required=true) MultipartFile file,HttpServletRequest request, HttpServletResponse response) {        PrintWriter out = null;        try {            //檔案儲存目錄路徑            String savePath = Global.getUploadPath() + "";            //檔案儲存目錄URL            String saveUrl  = "/";            //定義允許上傳的副檔名            HashMap<String, String> extMap = new HashMap<String, String>();            extMap.put("file", "xls,xlsx,csv");            //最大檔案大小            long maxSize = 20*1024*1024;            response.setContentType("text/html; charset=UTF-8");            out = response.getWriter();            //擷取社群個人檔案目錄            String permissionsDir = "";            if(!ServletFileUpload.isMultipartContent(request)){                return new ResultBean<>(201, "Please select a file.");            }            //檢查目錄            File uploadDir = new File(savePath);            if (!uploadDir.exists()) {                uploadDir.mkdirs();            }            String dirName = request.getParameter("dir");            if (dirName == null) {                dirName = "file";            }            //建立檔案夾            savePath += permissionsDir.length() > 0 ? permissionsDir + "/" + dirName + "/" : "/" + dirName + "/";            saveUrl += permissionsDir.length() > 0 ? permissionsDir + "/" + dirName + "/": "/" + dirName + "/";            File saveDirFile = new File(savePath);            if (!saveDirFile.exists()) {                saveDirFile.mkdirs();            }            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");            String ymd = sdf.format(new Date());            savePath += ymd + "/";            saveUrl += ymd + "/";            File dirFile = new File(savePath);            if (!dirFile.exists()) {                dirFile.mkdirs();            }            if (dirName.equals("file")) {                file.transferTo(new File(savePath+file.getOriginalFilename()));                System.out.println(savePath+file.getOriginalFilename());                CsvUtil util = new CsvUtil(savePath+file.getOriginalFilename());                int rowNum = util.getRowNum();                int colNum = util.getColNum();                if(rowNum<=101){                    boolean delResult=deleteFile(savePath+file.getOriginalFilename());                    if(delResult){                        log.info("del success");                    }else{                        log.info("del fail");                    }                    return new ResultBean<>(201, "The content of the file should be at least 100.");                }                List<String> columns=new ArrayList<String>();                for(int j=0;j<colNum;j++){                    String key=null;                    key=util.getString(0, j);                    columns.add(key);                }                System.out.println(columns);                Boolean result=true;                if(result){                    result=columns.contains("FirstName");                    if(result){                        result=columns.contains("LastName");                        if(result){                            result=columns.contains("Company");                            if(result){                                result=columns.contains("Address1");                                if(result){                                    result=columns.contains("City");                                    if(result){                                        result=columns.contains("State");                                        if(result){                                            result=columns.contains("Zip");                                            if(result){                                                result=columns.contains("Email");                                                if(result){                                                    result=columns.contains("Phone");                                                }                                            }                                        }                                    }                                }                            }                        }                    }                }                if(!result){                    boolean delResult=deleteFile(savePath+file.getOriginalFilename());                    if(delResult){                        log.info("del success");                    }else{                        log.info("del fail");                    }                    return new ResultBean<>(201, "File must contain the following columns:FirstName,LastName,Company,Address1,City,State,Zip,Email,Phone.");                }            }        } catch (Exception e) {            return new ResultBean<>(300, "fail");        }        return new ResultBean<>(200, "success");    }    private static boolean deleteFile(String path){        boolean del=false;        File file=new File(path);        if(file.isFile()){            file.delete();            del=true;        }        return del;    }}

java上傳下載參考:http://www.cnblogs.com/lcngu/p/5471610.html

angularjs + springmvc 上傳和下載

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.