Angularjs + springmvc upload and download

Source: Internet
Author: User
Tags log log



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 {

            / / File save directory path
            String savePath = Global.getUploadPath() + "";

            / / File save directory URL
            String saveUrl = "/";

            / / Define the file extension allowed to upload
            HashMap<String, String> extMap = new HashMap<String, String>();
            extMap.put("file", "xls,xlsx,csv");

            //Maximum file size
            Long maxSize = 20*1024*1024;

            response.setContentType("text/html; charset=UTF-8");
            Out = response.getWriter();

            / / Get the community personal file directory
            String permissionsDir = "";

            If(!ServletFileUpload.isMultipartContent(request)){
                Return new ResultBean<>(201, "Please select a file.");
            }
            / / Check the directory
            File uploadDir = new File(savePath);
            If (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            String dirName = request.getParameter("dir");
            If (dirName == null) {
                dirName = "file";
            }
            / / Create a folder
            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 upload Download reference: http://www.cnblogs.com/lcngu/p/5471610.html



Angularjs + springmvc upload and download


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.