resteay上传单个文件/多个文件到本地
代码如下:
CADLocalControlle.java
package com.xgt.controller; import com.xgt.common.BaseController; import com.xgt.common.PcsResult; import com.xgt.service.bs.ExcelService; import com.xgt.util.MD5Util; import org.apache.commons.io.IOUtils; 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.stereotype.Controller; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; /** * Created by Administrator on 2017/8/28. * 上传Excel到本地 */ @Controller @Path("/cadlocal") public class CADLocalController extends BaseController{ @Autowired private ExcelService excelService; private final String UPLOADED_FILE_PATH = "e:\\upload\\"; @POST @Path("/uploadLocalCAD") @Consumes(MediaType.MULTIPART_FORM_DATA ) @Produces(MediaType.APPLICATION_JSON) //@RequiresPermissions("picturelocal:uploadPicture") public PcsResult uploadFile(MultipartFormDataInput input) { String fileName = ""; Map<String, List<InputPart>> uploadForm = input.getFormDataMap(); List<InputPart> inputParts = uploadForm.get("fileselect[]"); for (InputPart inputPart : inputParts) { try { MultivaluedMap<String, String> header = inputPart.getHeaders(); fileName = getFileName(header); fileName = MD5Util.MD5(fileName+System.currentTimeMillis()); fileName = fileName+".dwg"; //convert the uploaded file to inputstream InputStream inputStream = inputPart.getBody(InputStream.class,null); byte [] bytes = IOUtils.toByteArray(inputStream); //constructs upload file path fileName = UPLOADED_FILE_PATH + fileName; writeFile(bytes,fileName); } catch (IOException e) { e.printStackTrace(); } } return newResult(true); } private String getFileName(MultivaluedMap<String, String> 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"; } //save to somewhere 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(); } }
BaseController.java
package com.xgt.common; import com.xgt.dao.entity.User; import com.xgt.exception.EnumPcsServiceError; import org.apache.shiro.SecurityUtils; import org.springframework.beans.factory.annotation.Value; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * Base controller which contains common methods for other controllers. */ public class BaseController { @Value("${default.pageSize}") private int defPageSize; @Value("${default.maxPageSize}") private int defMaxPageSize; @Value("${aliyunOSS.accessKeyId}") protected String accessKeyId; @Value("${aliyunOSS.accessKeySecret}") protected String accessKeySecret; @Value("${aliyunOSS.uploadUrl}") protected String endpoint; @Value("${aliyunOSS.bucketname}") protected String bucketName; @Value("${aliyunOSS.imageAddress}") protected String imageAddress; /** * Generate new PcsResult object, default with "SUCCESS" code. * * @return PcsResult result. */ protected PcsResult newResult() { PcsResult result = new PcsResult(); result.setCode(EnumPcsServiceError.SUCCESS.getCode()).setMessage(EnumPcsServiceError.SUCCESS.getDesc()); return result; } /** * Generate new PcsResult object, default with "SUCCESS" code. * * @return PcsResult result. */ protected PcsResult newResult(Boolean success) { PcsResult result = new PcsResult(); result.setSuccess(success); result.setCode(EnumPcsServiceError.SUCCESS.getCode()).setMessage(EnumPcsServiceError.SUCCESS.getDesc()); return result; } protected PcsResult failedResult(EnumPcsServiceError error) { PcsResult result = new PcsResult(); result.setCode(error.getCode()).setMessage(error.getDesc()); return result; } @SuppressWarnings("unused") protected PcsResult validateFailedResult(Integer errorCode, String description) { PcsResult result = new PcsResult(); result.setCode(errorCode).setMessage(description); return result; } @SuppressWarnings("unused") protected PcsResult validateFailedResult(EnumPcsServiceError error) { PcsResult result = new PcsResult(); result.setCode(error.getCode()).setMessage(error.getDesc()); return result; } protected Integer getLoginUserId(){ User user = (User) SecurityUtils.getSubject().getPrincipal(); return user.getUserId(); } protected List<Integer> getDepartmentUserIdList(){ User user = (User) SecurityUtils.getSubject().getPrincipal(); return user.getDepartmentUserIdList(); } /** * 构建 分页 页数 * @param page 页 * @return int */ protected int getCurPage(Integer page) { if (page==null || page<1) { return 1; } return page; } /** * 构建 分页 每页显示条数 * @param pageSize 每页显示条数 * @return int */ protected int getPageSize(Integer pageSize) { if (pageSize==null || pageSize<1) { return defPageSize; } if (pageSize>defMaxPageSize) { return defMaxPageSize; } return pageSize; } }
补充说明:
for (InputPart inputPart : inputParts) {}用于获得接收到的文件,可以接收多文件
fileName = MD5Util.MD5(fileName+System.currentTimeMillis());这里把文件名用MD5算法加密,不是为了加密,而是我在流中获取的中文文件名乱码,还没想好解决方案
fileName = fileName+".dwg";这里上传的是CAD文件,拼接后缀dwg
作者:Rest探路者
出处:http://www.cnblogs.com/Java-Starter/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意请保留此段声明,请在文章页面明显位置给出原文连接
Github:https://github.com/cjy513203427