本文整理汇总了Java中org.springframework.web.multipart.commons.CommonsMultipartFile类的典型用法代码示例。如果您正苦于以下问题:Java CommonsMultipartFile类的具体用法?Java CommonsMultipartFile怎么用?Java CommonsMultipartFile使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CommonsMultipartFile类属于org.springframework.web.multipart.commons包,在下文中一共展示了CommonsMultipartFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: upload
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
@RequestMapping(value = "/file/upload/{uploadId}", method = RequestMethod.POST)
@ResponseBody
public FileDto upload(@PathVariable String uploadId,
@RequestParam("data") CommonsMultipartFile multipart, HttpServletRequest request,
HttpServletResponse response) {
OutputStream out = null;
InputStream in = null;
try {
out = this.store.write(uploadId, multipart.getOriginalFilename(), multipart.getContentType());
in = multipart.getInputStream();
IOUtils.copy(in, out);
return this.store.getFileBean(uploadId);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
示例2: saveFile
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
public String saveFile(CommonsMultipartFile file) throws IOException {
String filePath = "/tmp/neilren4j_ip_" + new Date().getTime() + file.getOriginalFilename();
File newFile = new File(filePath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(newFile);
return filePath;
}
示例3: doClockIn
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
/**
*
* @Title: doClockIn
* @Description: 学生在教师拍照考勤时,没有检测到自己考勤
* @return
* BasicEntityVo<?>
*/
@RequestMapping("/clock-in")
@ResponseBody
public BasicEntityVo<?> doClockIn(String jwAccount, String loginAccount,
Double lng, Double lat, @RequestParam("clockinImg")CommonsMultipartFile file) {
if(StringUtils.isBlank(jwAccount)) {
return new BasicEntityVo<>(StudentClockInBusinessCode.JW_ACCOUNT_EMPTY[0], StudentClockInBusinessCode.JW_ACCOUNT_EMPTY[1]);
}
if(StringUtils.isBlank(loginAccount)) {
return new BasicEntityVo<>(StudentClockInBusinessCode.LOGIN_ACCOUNT_EMPTY[0], StudentClockInBusinessCode.LOGIN_ACCOUNT_EMPTY[1]);
}
if(lng == 0.0 || null == lng || lat == 0.0 || null == lat) {
return new BasicEntityVo<>(StudentClockInBusinessCode.LNG_LAT_EMPTY[0], StudentClockInBusinessCode.LNG_LAT_EMPTY[1]);
}
if(file.isEmpty()) {
return new BasicEntityVo<>(StudentClockInBusinessCode.BUSSINESS_IMAGE_EMPTY[0], StudentClockInBusinessCode.BUSSINESS_IMAGE_EMPTY[1]);
}
return clockinAsStudentService.clockin(jwAccount, loginAccount, lng, lat, file);
}
示例4: doUploadImageAjax
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
/**
* Upload an image using AJAX. The response will be returned as JSON object.
*
* @param request
* the servlet request
* @param userId
* the ID of the user whose image will be updated
* @return the JSON response object
*/
private ObjectNode doUploadImageAjax(HttpServletRequest request, Long userId) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile cFile = (CommonsMultipartFile) multipartRequest.getFile("file");
String errorMessage = null;
if (cFile != null && cFile.getSize() > 0) {
if (cFile.getSize() < getMaxUploadSize()) {
errorMessage = storeImage(request, cFile, userId);
} else {
errorMessage = MessageHelper.getText(request, "user.profile.upload.filesize.error",
new Object[] { FileUtils.byteCountToDisplaySize(getMaxUploadSize()) });
}
} else {
errorMessage = MessageHelper.getText(request, "user.profile.upload.empty.image");
}
if (errorMessage != null) {
return JsonRequestHelper.createJsonErrorResponse(errorMessage);
}
return JsonRequestHelper.createJsonSuccessResponse(null, createSuccessResult(userId));
}
示例5: setAttachment
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
@RequestMapping(value = "/attach/{id}", method = RequestMethod.POST)
public String setAttachment(@PathVariable("id") Long activityId,
@RequestParam("file") CommonsMultipartFile attachment,
WebRequest webRequest) {
IssueAttachmentFileUtil issueAttachmentFileUtil = new IssueAttachmentFileUtil();
Activity activity = activityService.find(activityId);
issueAttachmentFileUtil.deleteIfExcist(activity, servletContext);
activity.setFileName(attachment.getOriginalFilename());
activity = activityService.save(activity);
if (!attachment.isEmpty() && activity != null) {
issueAttachmentFileUtil.saveActivityAttachment(activity, attachment, servletContext);
}
return activity.getFileName();
}
示例6: migrate
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
@RequestMapping(method = RequestMethod.POST)
public ModelAndView migrate(@RequestParam("file") CommonsMultipartFile multipartFile,
@RequestParam(value = "description", required = false) String description,
WebRequest webRequest) {
SchemaVersion currentVersion = createCurrentVersion(multipartFile.getOriginalFilename(), description);
DatabaseWorker databaseWorker = new DatabaseWorker(dataSource, currentVersion, servletContext);
if (!databaseWorker.runScript(multipartFile)) {
schemeVersionService.delete(currentVersion.getId());
} else {
databaseWorker.createVersionDump();
}
return new ModelAndView("redirect:/test.html");
}
示例7: storeFile
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
public String storeFile(CommonsMultipartFile file, String userId,
String postTimestamp) {
try {
ObjectMetadata omd = new ObjectMetadata();
omd.setContentType("application/octet-stream");
omd.addUserMetadata("originalfilename", file.getOriginalFilename());
String path = "files/" + userId + "_" + postTimestamp.replace(':', '_') + "_" + file.getOriginalFilename();
PutObjectRequest request = new PutObjectRequest(BUCKET_NAME,
path,
file.getInputStream(), omd);
s3client.putObject(request);
s3client.setObjectAcl(BUCKET_NAME, path, CannedAccessControlList.PublicRead);
return "http://s3.amazonaws.com/" + BUCKET_NAME + "/" + path;
} catch (IOException e) {
return null;
}
}
示例8: storePicture
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
public String storePicture(CommonsMultipartFile file, String userId,
String postTimestamp) {
try {
ObjectMetadata omd = new ObjectMetadata();
omd.setContentType("application/octet-stream");
omd.addUserMetadata("originalfilename", file.getOriginalFilename());
String path = "pictures/" + userId + "_" + postTimestamp.replace(':', '_') + "_" + file.getOriginalFilename();
PutObjectRequest request = new PutObjectRequest(BUCKET_NAME,
path,
file.getInputStream(), omd);
s3client.putObject(request);
s3client.setObjectAcl(BUCKET_NAME, path, CannedAccessControlList.PublicRead);
return "http://s3.amazonaws.com/" + BUCKET_NAME + "/" + path;
} catch (IOException e) {
return null;
}
}
示例9: convertFilesToMap
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
/**
* This method converts the uploaded files into a map where the key is the
* file name and the value is the file content.
*/
public synchronized static Map<String, String> convertFilesToMap(CommonsMultipartFile[] fileInputList ) {
Map<String, String> fileMap = new LinkedHashMap<String, String>();
CommonsMultipartFile tmpMultiFile;
String tmpCharset;
fileNameCounterMap.clear();
for (int i = 0; i < fileInputList.length; i++) {
tmpMultiFile = fileInputList[i];
try {
if (tmpMultiFile != null && !tmpMultiFile.isEmpty() && tmpMultiFile.getInputStream() != null) {
tmpCharset = CrawlUtils.extractCharset(tmpMultiFile.getInputStream());
fileMap.put(
getFileName(tmpMultiFile.getOriginalFilename()),
tmpMultiFile.getFileItem().getString(tmpCharset));
}
} catch (IOException e) {}
}
return fileMap;
}
示例10: register
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
@Override
@Transactional(readOnly = false, rollbackFor = RuntimeException.class)
public BasicVo register(String phone, String smscode, String regID, CommonsMultipartFile[] files) {
// 检测数据库是否已有记录,这里检查是防止用户获取验证码成功后,更换一个已有的手机号输入
boolean hasPhone = smsCodeMapper.hasPhoneRegistered(phone).length > 0 ? true : false;
if(hasPhone) {
return new BasicVo(RegisterBusinessCode.BUSSINESS_PHONE_EXIST[0], RegisterBusinessCode.BUSSINESS_PHONE_EXIST[1]);
}
// 调用短信接口验证输入的短信验证码是否可用
boolean isVerify = SMSUtil.verifySmsCode(phone, smscode);
if(isVerify) {
BasicVo basicVo = null;
try {
SecurityAccountVo secAcc = new SecurityAccountVo();
secAcc.setSecurityAccount(phone);
secAcc.setSecuritSmsCode(smscode);
secAcc.setRegID(regID);
secAcc.setSecuritType(Student_User_Type);
// // 插入数据
registerMapper.saveRegisterInfo(secAcc);
secAcc = registerMapper.findAccountByPhone(phone);
LOG.info("secAcc="+secAcc);
fileSave(files, phone); // 保存上传的图片到临时位置
// 图片预处理
rawFaceProc(ImgStoragePath.RAW_FACE_IMG_SAVE_PATH+File.separator+phone,
ImgStoragePath.PROC_FACE_IMG_SAVE_PATH+File.separator+phone, secAcc.getFaceLabel());
// 生成CSV标签
generateCSV(ImgStoragePath.PROC_FACE_IMG_SAVE_PATH+File.separator+phone, ImgStoragePath.CSV_FILE_SAVE_PATH);
basicVo = new BasicVo(RegisterBusinessCode.BUSINESS_SUCCESS[0], RegisterBusinessCode.BUSINESS_SUCCESS[1]);
} catch(Exception e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
basicVo = new BasicVo(RegisterBusinessCode.BUSSINESS_FAILED[0], RegisterBusinessCode.BUSSINESS_FAILED[1]);
LOG.error("学生注册错误", e);
}
return basicVo;
}
return new BasicVo(RegisterBusinessCode.BUSSINESS_SMS_ERROR[0], RegisterBusinessCode.BUSSINESS_SMS_ERROR[1]);
}
示例11: documentAdjuntar
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
@RequestMapping(value = "/{tascaId}/document/{documentCodi}/adjuntar", method = RequestMethod.POST)
public String documentAdjuntar(
HttpServletRequest request,
@PathVariable String tascaId,
@PathVariable String documentCodi,
@RequestParam(value = "arxiu", required = false) final CommonsMultipartFile arxiu,
@RequestParam(value = "data", required = false) Date data,
Model model) {
try {
byte[] contingutArxiu = IOUtils.toByteArray(arxiu.getInputStream());
String nomArxiu = arxiu.getOriginalFilename();
ExpedientTascaDto tasca = tascaService.findAmbIdPerTramitacio(tascaId);
if (!tasca.isValidada()) {
MissatgesHelper.error(request, getMessage(request, "error.validar.dades"));
} else if (!expedientService.isExtensioDocumentPermesa(nomArxiu)) {
MissatgesHelper.error(request, getMessage(request, "error.extensio.document"));
} else if (nomArxiu.isEmpty() || contingutArxiu.length == 0) {
MissatgesHelper.error(request, getMessage(request, "error.especificar.document"));
} else {
accioDocumentAdjuntar(
request,
tascaId,
documentCodi,
nomArxiu,
contingutArxiu,
(data == null) ? new Date() : data).toString();
}
} catch (Exception ex) {
MissatgesHelper.error(request, getMessage(request, "error.guardar.document") + ": " + ex.getLocalizedMessage());
logger.error("Error al adjuntar el document a la tasca(" +
"tascaId=" + tascaId + ", " +
"documentCodi=" + documentCodi + ")",
ex);
}
return mostrarInformacioTascaPerPipelles(
request,
tascaId,
model,
"document");
}
示例12: documentModificarPost
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
@RequestMapping(value="/{expedientId}/documentAdjuntar", method = RequestMethod.POST)
public String documentModificarPost(
HttpServletRequest request,
@PathVariable Long expedientId,
@RequestParam(value = "accio", required = true) String accio,
@ModelAttribute DocumentExpedientCommand command,
@RequestParam(value = "arxiu", required = false) final CommonsMultipartFile arxiu,
@RequestParam(value = "processInstanceId", required = true) String processInstanceId,
BindingResult result,
SessionStatus status,
Model model) {
try {
new DocumentModificarValidator().validate(command, result);
if (result.hasErrors() || arxiu == null || arxiu.isEmpty()) {
if (arxiu == null || arxiu.isEmpty()) {
MissatgesHelper.error(request, getMessage(request, "error.especificar.document"));
}
model.addAttribute("processInstanceId", processInstanceId);
return "v3/expedientDocumentNou";
}
byte[] contingutArxiu = IOUtils.toByteArray(arxiu.getInputStream());
String nomArxiu = arxiu.getOriginalFilename();
command.setNomArxiu(nomArxiu);
command.setContingut(contingutArxiu);
expedientService.crearModificarDocument(expedientId, processInstanceId, null, command.getNom(), command.getNomArxiu(), command.getDocId(), command.getContingut(), command.getData());
MissatgesHelper.success(request, getMessage(request, "info.document.guardat") );
} catch (Exception ex) {
logger.error("No s'ha pogut crear el document: expedientId: " + expedientId, ex);
MissatgesHelper.error(request, getMessage(request, "error.proces.peticio") + ": " + ex.getLocalizedMessage());
}
return modalUrlTancar(false);
}
示例13: handleUploadClientLogo
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
/**
* Handle upload client logo.
*
* @param request
* the request
* @param errors
* the errors
* @param form
* the form backing object
* @return the model and view
*/
private ModelAndView handleUploadClientLogo(HttpServletRequest request, BindException errors,
ClientProfileLogoForm form) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile cFile = (CommonsMultipartFile) multipartRequest.getFile("file");
if (cFile == null || cFile.getSize() <= 0) {
MessageHelper.saveErrorMessageFromKey(request,
"client.change.logo.image.upload.empty.image");
return null;
}
ModelAndView mav = null;
long maxUploadSize = Long.parseLong(CommunoteRuntime.getInstance()
.getConfigurationManager().getApplicationConfigurationProperties()
.getProperty(ApplicationProperty.IMAGE_MAX_UPLOAD_SIZE));
if (cFile.getSize() < maxUploadSize) {
try {
byte[] dataLarge = cFile.getBytes();
ServiceLocator.instance().getService(ConfigurationManagement.class)
.updateClientLogo(dataLarge);
MessageHelper
.saveMessageFromKey(request, "client.change.logo.image.upload.success");
ServiceLocator.findService(ImageManager.class).imageChanged(
ClientImageDescriptor.IMAGE_TYPE_NAME,
ClientImageProvider.PROVIDER_IDENTIFIER, ClientHelper.getCurrentClientId());
form.setCustomClientLogo(true);
mav = new ModelAndView(getSuccessView(), getCommandName(), form);
} catch (Exception e) {
LOGGER.error("image upload failed", e);
String errorMsgKey = getImageUploadExceptionErrorMessageKey(e);
MessageHelper
.saveErrorMessage(request, MessageHelper.getText(request, errorMsgKey));
}
} else {
MessageHelper.saveErrorMessageFromKey(request,
"client.change.logo.image.upload.filesize.error");
}
return mav;
}
示例14: multipartFile2File
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
public static File multipartFile2File(MultipartFile file) {
CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) file;
DiskFileItem fileItem = (DiskFileItem) commonsMultipartFile.getFileItem();
File _file = fileItem.getStoreLocation();
return _file;
}
示例15: uploadImage
import org.springframework.web.multipart.commons.CommonsMultipartFile; //导入依赖的package包/类
/**
* Upload image.
*
* @param file the file
* @param principal the principal
* @return the map< string,? extends object>
*/
@RequestMapping(value = "/document/upload", method = RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> uploadImage(@RequestParam("file") CommonsMultipartFile file
, Principal principal) {
SasUser sasUser = JsonOutput.readSasUser(principal);
if (!file.isEmpty()) {
if (debug) {
System.out.println(
"file: " + file +
", name: " + file.getName() +
", contentType: " + file.getContentType() +
", originalFilename: " + file.getOriginalFilename() +
", extension: " + FilenameUtils.getExtension(file.getOriginalFilename()) +
", size: " + file.getSize() +
", defaultpath: " + filesSettings.getDocumentsDefaultPath()
);
}
try {
byte[] bytes = file.getBytes();
return JsonOutput.mapSuccess();
} catch (Exception e) {
return JsonOutput.mapError( "Failed to upload " + file.getOriginalFilename() + " => " + e.getMessage() );
}
} else {
return JsonOutput.mapError( "You failed to upload " + file.getOriginalFilename() + " because the file was empty." );
}
}