List of usage examples for org.springframework.web.multipart MultipartFile getName
String getName();
From source file:org.sakaiproject.assignment2.tool.beans.UploadBean.java
/** * Action Method Binding for the Upload Button on the initial page of the * upload workflow/wizard./*from w ww . j av a 2 s. co m*/ * * @return */ private WorkFlowResult processUploadGradesCSV(MultipartFile uploadedFile, Assignment2 assignment) { if (!AssignmentAuthoringBean.checkCsrf(csrfToken)) return WorkFlowResult.UPLOAD_FAILURE; // validation on file should have already occurred File newFile = null; try { newFile = File.createTempFile(uploadedFile.getName(), ".csv"); uploadedFile.transferTo(newFile); } catch (IOException ioe) { throw new UploadException(ioe.getMessage(), ioe); } // retrieve the displayIdUserId info once and re-use it Set<String> submitters = permissionLogic.getSubmittersInSite(assignment.getContextId()); displayIdUserIdMap = externalLogic.getUserDisplayIdUserIdMapForUsers(submitters); parsedContent = uploadGradesLogic.getCSVContent(newFile); // delete the file newFile.delete(); // ensure that there is not an unreasonable number of rows compared to // the number of students in the site int numStudentsInSite = displayIdUserIdMap.size(); int numRowsInUpload = parsedContent.size(); if (numRowsInUpload > (numStudentsInSite + 50)) { messages.addMessage(new TargettedMessage("assignment2.upload_grades.too_many_rows", new Object[] { numRowsInUpload, numStudentsInSite }, TargettedMessage.SEVERITY_ERROR)); return WorkFlowResult.UPLOADALL_CSV_UPLOAD_FAILURE; } // let's check that the students included in the file are actually in the site List<String> invalidDisplayIds = uploadGradesLogic.getInvalidDisplayIdsInContent(displayIdUserIdMap, parsedContent); if (invalidDisplayIds != null && !invalidDisplayIds.isEmpty()) { messages.addMessage(new TargettedMessage("assignment2.upload_grades.user_not_in_site", new Object[] { getListAsString(invalidDisplayIds) }, TargettedMessage.SEVERITY_ERROR)); return WorkFlowResult.UPLOADALL_CSV_UPLOAD_FAILURE; } // check that the grades are valid List<String> displayIdsWithInvalidGrade = uploadGradesLogic .getStudentsWithInvalidGradesInContent(parsedContent, assignment.getContextId()); if (displayIdsWithInvalidGrade != null && !displayIdsWithInvalidGrade.isEmpty()) { messages.addMessage(new TargettedMessage("assignment2.upload_grades.grades_not_valid", new Object[] { getListAsString(displayIdsWithInvalidGrade) }, TargettedMessage.SEVERITY_ERROR)); return WorkFlowResult.UPLOADALL_CSV_UPLOAD_FAILURE; } // let's proceed with the grade upload return WorkFlowResult.UPLOADALL_CSV_UPLOAD; }
From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
private String uploadFile(String collectionId) { String name = null;//from ww w. j a v a 2 s . c o m String mimeType = null; MultipartFile file = null; if (multipartMap.size() > 0) { // user specified a file, create it file = multipartMap.values().iterator().next(); } if (file != null) { // uploadsizeok would otherwise complain about 0 length file. For // this case it's valid. Means no file. if (file.getSize() == 0) return null; if (!uploadSizeOk(file)) return null; try { contentHostingService.checkCollection(collectionId); } catch (Exception ex) { try { ContentCollectionEdit edit = contentHostingService.addCollection(collectionId); edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, "LB-CSS"); contentHostingService.commitCollection(edit); } catch (Exception e) { setErrMessage(messageLocator.getMessage("simplepage.permissions-general")); return null; } } //String collectionId = getCollectionIdfalse); // user specified a file, create it name = file.getOriginalFilename(); if (name == null || name.length() == 0) name = file.getName(); int i = name.lastIndexOf("/"); if (i >= 0) name = name.substring(i + 1); String base = name; String extension = ""; i = name.lastIndexOf("."); if (i > 0) { base = name.substring(0, i); extension = name.substring(i + 1); } mimeType = file.getContentType(); try { ContentResourceEdit res = contentHostingService .addResource(collectionId, fixFileName(collectionId, Validator.escapeResourceName(base), Validator.escapeResourceName(extension)), "", MAXIMUM_ATTEMPTS_FOR_UNIQUENESS); res.setContentType(mimeType); res.setContent(file.getInputStream()); try { contentHostingService.commitResource(res, NotificationService.NOTI_NONE); // there's a bug in the kernel that can cause // a null pointer if it can't determine the encoding // type. Since we want this code to work on old // systems, work around it. } catch (java.lang.NullPointerException e) { setErrMessage(messageLocator.getMessage("simplepage.resourcepossibleerror")); } return res.getId(); } catch (org.sakaiproject.exception.OverQuotaException ignore) { setErrMessage(messageLocator.getMessage("simplepage.overquota")); return null; } catch (Exception e) { setErrMessage(messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString())); log.error("addMultimedia error 1 " + e); return null; } } else { return null; } }
From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
public void addMultimediaFile(MultipartFile file) { try {//from www . j av a 2 s. c o m String name = null; String sakaiId = null; String mimeType = null; if (file != null) { if (!uploadSizeOk(file)) return; String collectionId = getCollectionId(false); // user specified a file, create it name = file.getOriginalFilename(); if (name == null || name.length() == 0) name = file.getName(); int i = name.lastIndexOf("/"); if (i >= 0) name = name.substring(i + 1); String base = name; String extension = ""; i = name.lastIndexOf("."); if (i > 0) { base = name.substring(0, i); extension = name.substring(i + 1); } mimeType = file.getContentType(); try { ContentResourceEdit res = null; if (itemId != -1 && replacefile) { // upload new version -- get existing file SimplePageItem item = findItem(itemId); String resId = item.getSakaiId(); res = contentHostingService.editResource(resId); } else { // otherwise create a new file res = contentHostingService.addResource(collectionId, fixFileName(collectionId, Validator.escapeResourceName(base), Validator.escapeResourceName(extension)), "", MAXIMUM_ATTEMPTS_FOR_UNIQUENESS); } if (isCaption) res.setContentType("text/vtt"); else res.setContentType(mimeType); res.setContent(file.getInputStream()); try { contentHostingService.commitResource(res, NotificationService.NOTI_NONE); // there's a bug in the kernel that can cause // a null pointer if it can't determine the encoding // type. Since we want this code to work on old // systems, work around it. } catch (java.lang.NullPointerException e) { setErrMessage(messageLocator.getMessage("simplepage.resourcepossibleerror")); } sakaiId = res.getId(); if (("application/zip".equals(mimeType) || "application/x-zip-compressed".equals(mimeType)) && isWebsite) { // We need to set the sakaiId to the resource id of the index file sakaiId = expandZippedResource(sakaiId); if (sakaiId == null) return; // We set this special type for the html field in the db. This allows us to // map an icon onto website links in applicationContext.xml mimeType = "LBWEBSITE"; } } catch (org.sakaiproject.exception.OverQuotaException ignore) { setErrMessage(messageLocator.getMessage("simplepage.overquota")); return; } catch (Exception e) { setErrMessage( messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString())); log.error("addMultimedia error 1 " + e); return; } ; } else if (mmUrl != null && !mmUrl.trim().equals("") && multimediaDisplayType != 1 && multimediaDisplayType != 3) { // user specified a URL, create the item String url = mmUrl.trim(); // if user gives a plain hostname, make it a URL. // ui add https if page is displayed with https. I'm reluctant to use protocol-relative // urls, because I don't know whether all the players understand it. if (!url.startsWith("http:") && !url.startsWith("https:") && !url.startsWith("/")) { String atom = url; int i = atom.indexOf("/"); if (i >= 0) atom = atom.substring(0, i); // first atom is hostname if (atom.indexOf(".") >= 0) { String server = ServerConfigurationService.getServerUrl(); if (server.startsWith("https:")) url = "https://" + url; else url = "http://" + url; } } name = url; String basename = url; // SAK-11816 method for creating resource ID String extension = ".url"; if (basename != null && basename.length() > 32) { // lose the http first if (basename.startsWith("http:")) { basename = basename.substring(7); } else if (basename.startsWith("https:")) { basename = basename.substring(8); } if (basename.length() > 32) { // max of 18 chars from the URL itself basename = basename.substring(0, 18); // add a timestamp to differentiate it (+14 chars) Format f = new SimpleDateFormat("yyyyMMddHHmmss"); basename += f.format(new Date()); // total new length of 32 chars } } String collectionId; SimplePage page = getCurrentPage(); collectionId = getCollectionId(true); try { // urls aren't something people normally think of as resources. Let's hide them ContentResourceEdit res = contentHostingService .addResource(collectionId, fixFileName(collectionId, Validator.escapeResourceName(basename), Validator.escapeResourceName(extension)), "", MAXIMUM_ATTEMPTS_FOR_UNIQUENESS); res.setContentType("text/url"); res.setResourceType("org.sakaiproject.content.types.urlResource"); res.setContent(url.getBytes()); contentHostingService.commitResource(res, NotificationService.NOTI_NONE); sakaiId = res.getId(); } catch (org.sakaiproject.exception.OverQuotaException ignore) { setErrMessage(messageLocator.getMessage("simplepage.overquota")); return; } catch (Exception e) { setErrMessage( messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString())); log.error("addMultimedia error 2 " + e); return; } // connect to url and get mime type // new dialog passes the mime type if (multimediaMimeType != null && !"".equals(multimediaMimeType)) mimeType = multimediaMimeType; else mimeType = getTypeOfUrl(url); } else if (mmUrl != null && !mmUrl.trim().equals("") && (multimediaDisplayType == 1 || multimediaDisplayType == 3)) { // fall through. we have an embed code, don't need file } else // nothing to do return; // itemId tells us whether it's an existing item // isMultimedia tells us whether resource or multimedia // sameWindow is only passed for existing items of type HTML/XHTML // for new items it should be set true for HTML/XTML, false otherwise // for existing items it should be set to the passed value for HTML/XMTL, false otherwise // it is ignored for isMultimedia, as those are always displayed inline in the current page SimplePageItem item = null; if (itemId == -1 && isMultimedia) { item = appendItem(sakaiId, name, SimplePageItem.MULTIMEDIA); } else if (itemId == -1 && isWebsite) { String websiteName = name.substring(0, name.indexOf(".")); item = appendItem(sakaiId, websiteName, SimplePageItem.RESOURCE); } else if (itemId == -1) { item = appendItem(sakaiId, name, SimplePageItem.RESOURCE); } else if (isCaption) { item = findItem(itemId); if (item == null) return; item.setAttribute("captionfile", sakaiId); update(item); return; } else { item = findItem(itemId); if (item == null) return; // editing an existing item which might have customized properties // retrieve original resource and check for customizations ResourceHelper resHelp = new ResourceHelper(getContentResource(item.getSakaiId())); // if replacing file, keep existing name boolean hasCustomName = resHelp.isNameCustom(item.getName()) || replacefile; item.setSakaiId(sakaiId); if (!hasCustomName) { item.setName(name); } } // for new file, old captions don't make sense item.removeAttribute("captionfile"); // remember who added it, for permission checks item.setAttribute("addedby", getCurrentUserId()); item.setPrerequisite(this.prerequisite); if (mimeType != null) { item.setHtml(mimeType); } else { item.setHtml(null); } if (mmUrl != null && !mmUrl.trim().equals("") && isMultimedia) { if (multimediaDisplayType == 1) // the code is filtered by the UI, so the user can see the effect. // This protects against someone handcrafting a post. // The code is similar to that in submit, but currently doesn't // have folder-specific override (because there are no folders involved) item.setAttribute("multimediaEmbedCode", AjaxServer.filterHtml(mmUrl.trim())); else if (multimediaDisplayType == 3) item.setAttribute("multimediaUrl", mmUrl.trim()); item.setAttribute("multimediaDisplayType", Integer.toString(multimediaDisplayType)); } // if this is an existing item and a resource, leave it alone // otherwise initialize to false if (isMultimedia || itemId == -1) item.setSameWindow(false); clearImageSize(item); try { // if (itemId == -1) // saveItem(item); // else update(item); } catch (Exception e) { System.out.println("save error " + e); // saveItem and update produce the errors } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.springframework.integration.http.FileCopyingMultipartFileReader.java
public MultipartFile readMultipartFile(MultipartFile multipartFile) throws IOException { File upload = File.createTempFile(this.prefix, this.suffix, this.directory); multipartFile.transferTo(upload);/* w w w .j av a2 s . com*/ UploadedMultipartFile uploadedMultipartFile = new UploadedMultipartFile(upload, multipartFile.getSize(), multipartFile.getContentType(), multipartFile.getName(), multipartFile.getOriginalFilename()); if (logger.isDebugEnabled()) { logger.debug("copied uploaded file [" + multipartFile.getOriginalFilename() + "] to [" + upload.getAbsolutePath() + "]"); } return uploadedMultipartFile; }
From source file:siddur.solidtrust.classic.ClassicController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, Model model, HttpSession session) throws Exception { //upload// w w w. ja va 2s . co m log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); orders = persister.validateTitle(firstLine); //persist persister.parseAndSave(br, orders, persister); } finally { if (br != null) { br.close(); } } return "redirect:upload.html"; }
From source file:siddur.solidtrust.fault.FaultController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, @RequestParam("version") int v, Model model, HttpSession session) throws Exception { IFaultPersister persister = getPersister(v); //upload/* w ww .ja v a 2 s. c om*/ log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); orders = persister.validateTitle(firstLine); //persist persister.parseAndSave(br, orders, persister); } finally { if (br != null) { br.close(); } } return "redirect:upload.html"; }
From source file:siddur.solidtrust.newprice2.Newprice2Controller.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, Model model, HttpSession session) throws IOException { //upload// w ww . j a v a 2 s.c om log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } FileStatus fs = new FileStatus(); fs.setFile(temp); log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; String[] fields; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); fields = StringUtils.split(firstLine, ";"); ; orders = new int[fields.length]; for (int i = 0; i < orders.length; i++) { orders[i] = ArrayUtils.indexOf(FIELDS, fields[i].trim()); } //count while (br.readLine() != null) { fs.next(); } } finally { if (br != null) { br.close(); } } fs.flip(); log4j.info("Total rows: " + fs.getTotalRow()); //persist carService.saveCars(fs, orders, carService); return "redirect:/v2/upload.html"; }
From source file:ua.aits.Carpath.controller.FileUploadController.java
/** * Upload single file using Spring Controller * @param file/* ww w. ja va 2s . com*/ * @param path * @param request * @return */ @RequestMapping(value = { "/uploadFile", "/Carpath/uploadFile", }, method = RequestMethod.POST) public @ResponseBody String uploadFileHandler(@RequestParam("upload") MultipartFile file, @RequestParam("path") String path, HttpServletRequest request) { String name = file.getOriginalFilename(); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // Creating the directory to store file File dir = new File(Constants.HOME + path); if (!dir.exists()) dir.mkdirs(); // Create the file on server File serverFile = new File(dir.getAbsolutePath() + File.separator + name); try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) { stream.write(bytes); } String link_path = serverFile.getAbsolutePath().replace(Constants.HOME, ""); return "<a href=\"#\" class=\"returnImage\" data-url='" + Constants.URL + path + name + "'>" + "<img src=\"" + Constants.URL + link_path + "\" realpath='" + link_path + "' alt='" + link_path + file.getName() + "' /><img src='" + Constants.URL + "img/remove.png' class='remove-icon'/></a>"; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }
From source file:ubic.gemma.web.util.upload.CommonsMultipartMonitoredResolver.java
@Override public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException { String enc = determineEncoding(request); ServletFileUpload fileUpload = this.newFileUpload(request); DiskFileItemFactory newFactory = (DiskFileItemFactory) fileUpload.getFileItemFactory(); fileUpload.setSizeMax(sizeMax);/*from ww w . ja va2s. c om*/ newFactory.setRepository(this.uploadTempDir); fileUpload.setHeaderEncoding(enc); try { MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>(); Map<String, String[]> multipartParams = new HashMap<>(); // Extract multipart files and multipart parameters. List<?> fileItems = fileUpload.parseRequest(request); for (Object fileItem1 : fileItems) { FileItem fileItem = (FileItem) fileItem1; if (fileItem.isFormField()) { String value; String fieldName = fileItem.getFieldName(); try { value = fileItem.getString(enc); } catch (UnsupportedEncodingException ex) { logger.warn("Could not decode multipart item '" + fieldName + "' with encoding '" + enc + "': using platform default"); value = fileItem.getString(); } String[] curParam = multipartParams.get(fieldName); if (curParam == null) { // simple form field multipartParams.put(fieldName, new String[] { value }); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParams.put(fieldName, newParam); } } else { // multipart file field MultipartFile file = new CommonsMultipartFile(fileItem); multipartFiles.set(file.getName(), file); if (logger.isDebugEnabled()) { logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "]"); } } } return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParams, null); } catch (FileUploadException ex) { return new FailedMultipartHttpServletRequest(request, ex.getMessage()); } }
From source file:uk.ac.abdn.fits.support.thymeleaf.springmail.web.MailController.java
@RequestMapping(value = "/sendMailWithInlineImage", method = RequestMethod.POST) public String sendMailWithInline(@RequestParam("recipientName") final String recipientName, @RequestParam("recipientEmail") final String recipientEmail, @RequestParam("image") final MultipartFile image, final Locale locale) throws MessagingException, IOException { this.emailService.sendMailWithInline(recipientName, recipientEmail, image.getName(), image.getBytes(), image.getContentType(), locale); return "redirect:sent.html"; }