web下图片上传并预览

html代码:

<form id="upload" name="upload">
    <div class="upload-div" style="margin-top: 20px">
        <label class="btn gray" for="input-upload" style="display: inline-block; width: 100px">上传图片</label>
        <input type="file" name="file" id="input-upload" style="display: inline"/>
        <h5 class="h5-gray" style="display: inline;margin-left: 10px">宽高大于800px * 480px, 不得超过5M</h5>
    </div>
    <div class="upload-list">
        <img id="add-pictureUrl" src="../../../static/png/img_default_goods.png"/>
    </div>
</form>

 

js代码:

* String requestUri = "/views/commodity/upload";

* String fileElement = $("#input-upload");

* String picElement = $("#add-pictureUrl");

fileElement.on("change", function () {

    var filePath = $(this).val();
    if (filePath.indexOf("jpg") != -1 || filePath.indexOf("png") != -1) {
        var formData = new FormData($("#upload")[0]);
        formData.append('file', fileElement.val());

        $.ajax({
            type: 'POST',
            dataType: 'json',
            data: formData,
            url: requestUri,
            enctype: 'multipart/form-data',
            contentType: false,//必须有
            processData: false,//必须有

            success: function (result) {
                if (result.code == 1) {
                    picElement.attr("src", result.body);
                } else {
                    alert(result.message);
                }
            },
            error: function (d) {
                console.log(d);
                alert("图片不符合要求,请重新上传");
            }
        });
    } else {
        alert("您上传文件类型有误!");
        return false
    }
});

controller代码:

* String rootDir = "/Users/mac/app"; (mac下路径)

* String rootDir = "C:/Users/sandy/app"; (win下路径)

@ResponseBody
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public JsonResponseDto handleFileUpload(@PathParam(value = "file") MultipartFile file) throws IOException {

    if (!file.isEmpty()) {
        if (file.getSize() > uploadPicSize) {
            return JsonResponseDto.FAILURE().setMessage("文件不得超过5M.");
        }
        BufferedImage bi = ImageIO.read(file.getInputStream());
        if (bi.getWidth() < uploadPicWidth || bi.getHeight() < uploadPicHeight) {
            return JsonResponseDto.FAILURE().setMessage("文件尺寸不正确");
        }
        String myFileName = file.getOriginalFilename();
        if (myFileName.trim() != "") {
            String uploadPicFolder = rootDir + AppConstant.UPLOAD_PIC_COMMODITY;
            String picUri = fileService.saveFile(file, uploadPicFolder);
            return JsonResponseDto.SUCCESS().setBody(picUri);
        }
    }
    return JsonResponseDto.FAILURE().setMessage("File is invalid.");

}

图片上传service

/*
 *
 *  *  Copyright (c) 2017. For Intelligent Group.
 *  *
 *
 */
package com.intelligent.hato.cs.service.core.service.impl;
import com.intelligent.hato.cs.service.core.config.RouteConfig;
import com.intelligent.hato.cs.service.core.service.FileService;
import com.intelligent.hato.cs.service.core.utils.FileUploadUtil;
import com.intelligent.hato.cs.service.core.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.util.UUID;

/**
 * Created by cherry on 2017/11/27.
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private RouteConfig routeConfig;

    Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    public String saveFile(MultipartFile file, String filePath) {
        //扩展名格式
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String name;
        /**
         * 指定上传目录
         */
        if (filePath != null && !"".equals(filePath.trim())) {
            name = designatedUp(filePath, file);
            return name;
        }
        /**
         * 默认上传目录
         */
        //图片类型文件
        if (this.inArray(routeConfig.getImageType(), extName)) {
            filePath = routeConfig.getUploadDefaultDir();
        } else {
            return "This upload type is not supported temporarily";
        }
        name = myFileUp(filePath, file);
        return name;
    }

    public String removeFile(String filePath) {
        try {
            FileUtil.removeFile(routeConfig.getUploadDefaultDir() + File.separator + filePath);
            return "successful operation";
        } catch (Exception e) {
            return "drop file error";
        }
    }

    /**
     * 判断数组中是否包含某个元素
     *
     * @param array   类型的数组
     * @param element 被检查的类型
     * @return
     */
    private boolean inArray(String[] array, String element) {
        boolean flag = false;
        for (String type : array) {
            if (element.equals(type)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 默认上传文件到文件夹
     *
     * @param folder 默认文件夹
     * @param file   上传的文件
     * @return
     */
    private String myFileUp(String folder, MultipartFile file) {
        LocalDate today = LocalDate.now();
        String saveName = File.separator + today.getYear() + "." + today.getMonthValue() + File.separator;
        String fileCode = UUID.randomUUID().toString().trim().replaceAll("-", "");
        String returnName = FileUploadUtil.fileUp(file, routeConfig.getUploadDefaultDir() + File.separator + folder + saveName, fileCode);
        saveName = folder + File.separator + saveName + File.separator + returnName;
        logger.warn("This file has been uploaded: " + saveName);
        return saveName;
    }

    /**
     * 指定目录上传文件
     *
     * @param folder 指定文件夹
     * @param file   上传文件
     * @return
     */
    private String designatedUp(String folder, MultipartFile file) {
        String fileCode = UUID.randomUUID().toString().trim().replaceAll("-", "");
//        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        String returnName = FileUploadUtil.fileUp(file, folder, fileCode);
        folder = (folder.contains(":") ? folder.split(":")[1] : folder);
        String filePathname = folder + "/" + returnName;
        logger.warn("This file has been uploaded: " + filePathname);
        return filePathname;
    }

}

图片上传工具类

/*
 *
 *  *  Copyright (c) 2017. For Intelligent Group.
 *  *
 *
 */

package com.intelligent.hato.cs.service.core.utils;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by cherry on 2017/11/27.
 */
public class FileUploadUtil {

    /**
     * @param file     //文件对象
     * @param filePath //上传路径
     * @param fileName //文件名
     * @return 文件名
     */
    public static String fileUp(MultipartFile file, String filePath, String fileName) {
        String extName = ""; // 扩展名格式:
        try {
            if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
                extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            }
            copyFile(file.getInputStream(), filePath, fileName + extName).replaceAll("-", "");
        } catch (IOException e) {
            System.out.println(e);
        }
        return fileName + extName;
    }
    /**
     * 写文件到当前目录的upload目录中
     *
     * @param in
     * @param dir
     * @param realName
     * @throws IOException
     */
    private static String copyFile(InputStream in, String dir, String realName)
            throws IOException {
        File file = new File(dir, realName);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        FileUtils.copyInputStreamToFile(in, file);
        return realName;
    }

}

静态资源处理 WebResourceConfig

package com.intelligent.hato.cs.web.config;
import com.intelligent.hato.cs.web.utils.AppConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.io.File;
/**
 * Created by Can.Guan on 2017/11/14.
 */
@Configuration
public class WebResourceConfig extends WebMvcConfigurerAdapter {

    @Value("${app.path.root}")
    private String rootDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/css/**", "/views/static/css/**")
                .addResourceLocations("classpath:/static/css/");
        registry.addResourceHandler("/static/fonts/**", "/views/static/fonts/**")
                .addResourceLocations("classpath:/static/fonts/");
        registry.addResourceHandler("/static/js/**", "/views/static/js/**")
                .addResourceLocations("classpath:/static/js/");
        registry.addResourceHandler("/static/png/**", "/views/static/png/**")
                .addResourceLocations("classpath:/static/png/");

        registry.addResourceHandler("/static/upload/commodity/**")
                .addResourceLocations("classpath:/static/upload/commodity/");
        registry.addResourceHandler("/static/upload/default/**")
                .addResourceLocations("classpath:/static/upload/default/");
        registry.addResourceHandler("/static/upload/box/**")
                .addResourceLocations("classpath:/static/upload/box/");
        registry.addResourceHandler("/fragment/**")
                .addResourceLocations("classpath:/templates/fragment/");

        String defaultPicUploadPath = rootDir + AppConstant.UPLOAD_PIC_DEFAULT;
        String commodityPicUploadPath = rootDir + AppConstant.UPLOAD_PIC_COMMODITY;
        String boxPicUploadPath = rootDir + AppConstant.UPLOAD_PIC_BOX;
        if (defaultPicUploadPath != null) {
            defaultPicUploadPath.replace(":", ":");
            String filePath = (defaultPicUploadPath.contains(":") ? defaultPicUploadPath.split(":")[1] : defaultPicUploadPath);
            registry.addResourceHandler(filePath + "/**")
                    .addResourceLocations("file:///" + defaultPicUploadPath);
        }
        if (commodityPicUploadPath != null) {
            commodityPicUploadPath.replace(":", ":");
            String filePath = (commodityPicUploadPath.contains(":") ? commodityPicUploadPath.split(":")[1] : commodityPicUploadPath);
            registry.addResourceHandler(filePath + "/**")
                    .addResourceLocations("file:///" + commodityPicUploadPath + "/");
        }
        if (boxPicUploadPath != null) {
            boxPicUploadPath.replace(":", ":");
            String filePath = (boxPicUploadPath.contains(":") ? boxPicUploadPath.split(":")[1] : boxPicUploadPath);
            registry.addResourceHandler(filePath + "/**")
                    .addResourceLocations("file:///" + boxPicUploadPath + "/");
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值