rest服务中通过resteasy方式上传文件

resteasy服务器代码

Control:
import com.mochasoft.latte.commons.log.BaseLogger;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.io.IOException;
@Controller
@Path(value = "/file")
public class FileUploadRest extends BaseLogger {
    @Autowired
    private IFileUploadService fileUploadService;

    /**
     * 日志文件上传
     *
     * @param
     * @return
     * @throws IOException
     */
    @POST
    @Path("/upload")
    @Consumes("multipart/form-data")
    @Produces("application/json;charset=UTF-8")
    public Object uploadFile( MultipartFormDataInput input) throws IOException {
        return fileUploadService.uploadFile(input);
    }
}
ServiceIml:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.ws.rs.core.MultivaluedMap;
import java.io.*;
import java.util.*;

import static com.mochasoft.zjlms.manage.constants.ManageConstants.UPLOADED_FILE_PATH;

@Service
public class FileUploadServiceImpl extends BaseLogger implements IFileUploadService {
    String path=System.getProperty("user.dir")+"\\upload\\";

    /**
     * 日志数据上传
     *
     * @param jsonData
     * @return
     */
    public Object uploadFile(MultipartFormDataInput input) {
        String fileName = "";
        try {
            //Get API input data
            Map> uploadForm = input.getFormDataMap();
            List inputParts = uploadForm.get("file");
            for (InputPart inputPart : inputParts) {
                try {
                    MultivaluedMap header = inputPart.getHeaders();
                    fileName = getFileName(header);
                    //convert the uploaded file to inputstream
                    InputStream inputStream = inputPart.getBody(InputStream.class,null);
                    byte [] bytes = IOUtils.toByteArray(inputStream);
                    double fileSize = Double.parseDouble(bytes.length + "") / 1024 / 1024;
                    if(fileSize > 200){
                        return R.error(10001,"必须参数大小不能超过规定范围");
                    }
                    //constructs upload file path
                    fileName = path + fileName;
                   // 截取上传文件后缀
                    String extName = fileName.substring(fileName.indexOf(".") + 1).toLowerCase().trim();
                    // 判断后缀
                    String fileType = "txt,log";
                    writeFile(bytes,fileName);
                    logger.info("日志文件上传成功: " + fileName);
                } catch (Exception e) {
                    logger.error("日志文件上传失败--", e);
                    continue;
                }
            }
        } catch (Exception e) {
            logger.error("日志数据上传异常--", e);
        }
        return R.ok();
    }

    /**
     * 写文件到本地目录
     *
     * @param content
     * @param filename
     * @throws IOException
     */
    private void writeFile(byte[] content, String filename) throws IOException {
        File file = new File(filename);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fop = new FileOutputStream(file);
        fop.write(content);
        fop.flush();
        fop.close();
    }
    /**
     * 获取filename
     *
     * @param header
     * @throws IOException
     */
    private String getFileName(MultivaluedMap header) {
        String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
        for (String filename : contentDisposition) {
            if ((filename.trim().startsWith("filename"))) {
                String[] name = filename.split("=");
                String finalFileName = name[1].trim().replaceAll("\"", "");
                return finalFileName;
            }
        }
        return "unknown";
    }

你可能感兴趣的:(upload,rest-api,resteasy)