angularjs + springmvc 上传和下载

Posted qiuri2008

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了angularjs + springmvc 上传和下载相关的知识,希望对你有一定的参考价值。

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 上传和下载的主要内容,如果未能解决你的问题,请参考以下文章

Spring MVC - AngularJS - 文件上传 - org.apache.commons.fileupload.FileUploadException

Spring MVC 和 Angularjs

AngularJS 和 Spring MVC 安全性

SpringMVC_[4]文件上传和下载

SpringMVC_[4]文件上传和下载

使用 AngularJS 配置 Spring MVC