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

原文地址:https://www.cnblogs.com/jiangzhaowei/p/9483376.html

时间: 2024-11-05 20:32:23

angularjs + springmvc 上传和下载的相关文章

springMVC上传与下载

springMVC上传与下载 首先,springmvc.xml必须配置: Java代码 1.      <bean id="multipartResolver" 2.              class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/> <bean id="m

myBatis + SpringMVC上传、下载文件

环境:maven+SpringMVC + Spring + MyBatis + MySql 本文主要说明如何使用input上传文件到服务器指定目录,或保存到数据库中:如何从数据库下载文件,和显示图像文件并实现缩放. 将文件存储在数据库中,一般是存文件的byte数组,对应的数据库数据类型为blob. 首先要创建数据库,此处使用MySql数据库. 注意:文中给出的代码多为节选重要片段,并不齐全. 1.  前期准备 使用maven创建一个springMVC+spring+mybatis+mysql的项

webAPI+angularJS文件上传和下载

开发框架 前端 angularJS1.6 下载和保存文件FileSaver:https://github.com/eligrey/FileSaver.js/ 后端 .net WebAPI 1 导入Excel文件关键代码 1.1 导入Excel弹出框 1.2 模态框html代码 <div class="modal fade" id="importExcelPop" tabindex="-1" role="dialog" a

springMVC上传和下载附件

上传: 导入需要的jar包:Spring MVC类库 + 文件上传下载需要的JAR包,图中A处为文件上传下载需要的JAR包,其余为Spring MVC类库. 构建领域模层:model层和control层.view层 FileController: 1 package com.controller.system; 2 3 import java.io.FileOutputStream; 4 import java.io.OutputStream; 5 import java.text.Simple

转载:SpringMVC:上传与下载

1 springmvc.xml必须配置: Java代码   <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/> Java代码   <bean id="multipartResolver" class=

Spring MVC 上传、下载、显示图片

通过这篇文章你可以了解到: 使用 SpringMVC 框架,上传图片,并将上传的图片保存到文件系统,并将图片路径持久化到数据库 在 JSP 页面上实现显示图片.下载图片 [TOC] 1. 准备工作 首先我们需要准备好开发环境,本文测试环境是 SSM(Spring 4.3.9 + SpringMVC 4.3.9 + MyBatis 3.4.4) ,数据库为 MySQL 5.5,数据库连接池 C3P0 0.9.5.2,构建包 Maven 3.5.0,Tomcat 8.5. 限于篇幅原因,关于 SSM

springmvc和servlet下的文件上传和下载(存文件目录和存数据库Blob两种方式)

项目中涉及了文件的上传和下载,以前在struts2下做过,今天又用springmvc做了一遍,发现springmvc封装的特别好,基本不用几行代码就完成了,下面把代码贴出来: FileUpAndDown.jsp <%@ page language="java" contentType="text/html; charset=UTF-8"%> <html> <head> <title>using commons Uplo

springmvc和servlet在上传和下载文件(保持文件夹和存储数据库Blob两种方式)

参与该项目的文件上传和下载.一旦struts2下完成,今天springmvc再来一遍.发现springmvc特别好包,基本上不具备的几行代码即可完成,下面的代码贴: FileUpAndDown.jsp <%@ page language="java" contentType="text/html; charset=UTF-8"%> <html> <head> <title>using commons Upload to

SpringMVC实现文件的上传和下载

前些天一位江苏经贸的学弟跟我留言问了我这样一个问题:"用什么技术来实现一般网页上文件的上传和下载?是框架还是Java中的IO流".我回复他说:"使用SpringMVC框架可以做到这一点,因为SpringMVC为文件的上传提供了直接的支持,但需要依赖Apache提供Commons FileUpload组件jar包."鉴于这个问题,我上网也百度了一下,网上很多都是介绍的使用IO流来实现文件的上传和下载,也有说到框架的,但介绍的并不是很完整,今天小钱将和大家介绍使用Spr