本文整理匯總了Java中org.springframework.web.multipart.MultipartFile類的典型用法代碼示例。如果您正苦於以下問題:Java MultipartFile類的具體用法?Java MultipartFile怎麽用?Java MultipartFile使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
MultipartFile類屬於org.springframework.web.multipart包,在下文中一共展示了MultipartFile類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: upload
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
/**
* 上傳文件
*/
@RequestMapping("/upload")
@RequiresPermissions("sys:oss:all")
public R upload(@RequestParam("file") MultipartFile file) throws Exception {
if (file.isEmpty()) {
throw new RRException("上傳文件不能為空");
}
//上傳文件
String url = OSSFactory.build().upload(file.getBytes());
//保存文件信息
SysOssEntity ossEntity = new SysOssEntity();
ossEntity.setUrl(url);
ossEntity.setCreateDate(new Date());
sysOssService.save(ossEntity);
return R.ok().put("url", url);
}
示例2: uploadAvatar
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
@RequestMapping(value = "/{id}/uploadAvatar", method = RequestMethod.POST)
@ApiOperation(value = "Add new upload Avatar")
public String uploadAvatar(@ApiParam(value = "user Id", required = true) @PathVariable("id") Integer id,
@ApiParam(value = "Image File", required = true) @RequestPart("file") MultipartFile file) {
String contentType = file.getContentType();
if (!FileUploadUtil.isValidImageFile(contentType)) {
return "Invalid image File! Content Type :-" + contentType;
}
File directory = new File(AVATAR_UPLOAD.getValue());
if (!directory.exists()) {
directory.mkdir();
}
File f = new File(userService.getAvatarUploadPath(id));
try (FileOutputStream fos = new FileOutputStream(f)) {
byte[] imageByte = file.getBytes();
fos.write(imageByte);
return "Success";
} catch (Exception e) {
return "Error saving avatar for User " + id + " : " + e;
}
}
示例3: player
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
public player(String playerId, String firstName, String lastName,
String fullName, String alias, Date date, String email,
String phoneNumber, String twitterHandle, String instagramHandle,
String teamSelected, String teamCountry, String location, String reference,
int playerGroup, String mailStatus, boolean fixtureGenerated, boolean inTables, MultipartFile image) {
PlayerId = playerId;
this.firstName = firstName;
this.lastName = lastName;
this.fullName = fullName;
this.alias = alias;
this.date = date;
this.email = email;
this.phoneNumber = phoneNumber;
this.twitterHandle = twitterHandle;
this.instagramHandle = instagramHandle;
this.teamSelected = teamSelected;
this.teamCountry = teamCountry;
this.location = location;
this.reference = reference;
this.playerGroup = playerGroup;
this.mailStatus = mailStatus;
this.fixtureGenerated = fixtureGenerated;
this.inTables = inTables;
this.image = image;
}
示例4: generateFromHtml
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
@APIDeprecated(
name = "/api/v1/pdf-generator/html",
docLink = "https://github.com/hmcts/cmc-pdf-service#standard-api",
expiryDate = "2018-02-08",
note = "Please use `/pdfs` instead.")
@ApiOperation("Returns a PDF file generated from provided HTML/Twig template and placeholder values")
@PostMapping(
value = "/html",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_PDF_VALUE
)
public ResponseEntity<ByteArrayResource> generateFromHtml(
@ApiParam("A HTML/Twig file. CSS should be embedded, images should be embedded using Data URI scheme")
@RequestParam("template") MultipartFile template,
@ApiParam("A JSON structure with values for placeholders used in template file")
@RequestParam("placeholderValues") String placeholderValues
) {
log.debug("Received a PDF generation request");
byte[] pdfDocument = htmlToPdf.convert(asBytes(template), asMap(placeholderValues));
log.debug("PDF generated");
return ResponseEntity
.ok()
.contentLength(pdfDocument.length)
.body(new ByteArrayResource(pdfDocument));
}
示例5: uploadImHeadPortrait
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
/**
* Im頭像上傳
*
* @param file
* @return
* @throws Exception
*/
@RequestMapping("uploadImHeadPortrait")
@ResponseBody
public PageData uploadImHeadPortrait(MultipartFile[] file) throws Exception {
PageData pd = fileUpd(file);
Object content = pd.get("content");
PageData returnPd = new PageData();
if (pd.getString("state").equals("200")) {
String path = (String) ((HashMap) ((List) content).get(0)).get("path");
String sltpath = (String) ((HashMap) ((List) content).get(0)).get("sltpath");
PageData returnPd1 = new PageData();
returnPd1.put("src", path);
returnPd1.put("srcSlt", sltpath);
returnPd.put("code", "0");
returnPd.put("msg", "success");
returnPd.put("data", returnPd1);
return WebResult.requestSuccess(returnPd);
} else {
return WebResult.requestFailed(500, "服務器錯誤", pd.get("content"));
}
}
示例6: update
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
/**
* @api {patch} /credentials/:name Update
* @apiParam {String} name Credential name to update
*
* @apiParamExample {multipart} RSA-Multipart-Body:
* the same as create
*
* @apiGroup Credenital
*/
@PatchMapping(path = "/{name}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@WebSecurity(action = Actions.ADMIN_UPDATE)
public Credential update(@PathVariable String name,
@RequestParam(name = "detail") String detailJson,
@RequestPart(name = "android-file", required = false) MultipartFile androidFile,
@RequestPart(name = "p12-files", required = false) MultipartFile[] p12Files,
@RequestPart(name = "pp-files", required = false) MultipartFile[] ppFiles) {
// check name is existed
if (!credentialService.existed(name)) {
throw new IllegalParameterException("Credential name does not existed");
}
CredentialDetail detail = jsonConverter.getGsonForReader().fromJson(detailJson, CredentialDetail.class);
return createOrUpdate(name, detail, androidFile, p12Files, ppFiles);
}
示例7: upload
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
@ResponseBody
@RequestMapping(value = "upload.do",method = RequestMethod.POST)
public ServerResponse upload(HttpSession session,@RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request){
// TODO: 2017/8/4 這個required = false是指upload_file不是必須加的嗎?
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"請先登錄");
}
//判斷這個用戶是不是管理員
ServerResponse<String> checkRoleResult = iUserService.checkUserRole(user);
if (checkRoleResult.isSuccess()){
//tomcat發布以後,會在webapp下創建一個upload文件夾,與index.jsp和WEB-INF同級
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = iFileService.upload(file, path);
String url = PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/")
+fileName;
Map map = Maps.newHashMap();
map.put("uri",fileName);
map.put("url",url);
return ServerResponse.createBySuccess(map);
} else {
return ServerResponse.createByError("對不起,您沒有管理員權限");
}
}
示例8: testCreateFromDocuments
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
@Test
public void testCreateFromDocuments() throws Exception {
List<MultipartFile> files = Stream.of(
new MockMultipartFile("files", "filename.txt", "text/plain", "hello".getBytes(StandardCharsets.UTF_8)),
new MockMultipartFile("files", "filename.txt", "text/plain", "hello2".getBytes(StandardCharsets.UTF_8)))
.collect(Collectors.toList());
List<StoredDocument> storedDocuments = files.stream().map(f -> new StoredDocument()).collect(Collectors.toList());
when(this.auditedStoredDocumentOperationsService.createStoredDocuments(files)).thenReturn(storedDocuments);
restActions
.withAuthorizedUser("userId")
.withAuthorizedService("divorce")
.postDocuments("/documents", files, Classifications.PUBLIC, null)
.andExpect(status().isOk());
}
示例9: saveUploadedFiles
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
private String saveUploadedFiles(List<MultipartFile> files) throws IOException {
if (Files.notExists(Paths.get(UPLOADED_FOLDER))) {
init();
}
String randomPath = "";
for (MultipartFile file : files) {
if (file.isEmpty()) {
continue; //next pls
}
byte[] bytes = file.getBytes();
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
randomPath += generateRandomPath() + "." + suffix;
Path path = Paths.get(UPLOADED_FOLDER + randomPath);
Files.write(path, bytes);
}
return randomPath;
}
示例10: fileUpload
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
String fileUpload(MultipartFile file, ProjectFile pTarFile) {
try {
//decode
pTarFile.setPFNotice(new String(pTarFile.getPFNotice().getBytes("iso-8859-1"), "UTF-8"));
String realFileName = new String(file.getOriginalFilename().getBytes("iso-8859-1"), "UTF-8");
String suffix = realFileName.substring(realFileName.lastIndexOf(".") + 1);
String savaFileStr = DateTime.now().toString() + "." + suffix;
String PFId = projectService.addFiletoUWid(savaFileStr, pTarFile, file);
pTarFile.setPFId(PFId);
//動態生成更新字段
dynamicService.setProjectFileDynamic(pTarFile);
return "ok";
} catch (IOException e) {
e.printStackTrace();
}
return "error:您沒有在該階段上傳的權限";
}
示例11: upload
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
@RequestMapping("/upload.do")
public String upload(@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException {
for(MultipartFile file : myfiles){
//此處MultipartFile[]表明是多文件,如果是單文件MultipartFile就行了
if(file.isEmpty()){
System.out.println("文件未上傳!");
}
else{
//得到上傳的文件名
String fileName = file.getOriginalFilename();
//得到服務器項目發布運行所在地址
String path1 = request.getSession().getServletContext().getRealPath("file")+ File.separator;
// 此處未使用UUID來生成唯一標識,用日期做為標識
String path2 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ fileName;
request.getSession().setAttribute("document",path2);
String path = path1+path2;
//查看文件上傳路徑,方便查找
System.out.println(path);
//把文件上傳至path的路徑
File localFile = new File(path);
file.transferTo(localFile);
}
}
return "redirect:/student/uploadDocument";
}
示例12: store
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
/**
* The storing method should be able to adapt to all types of storing: requests, templates and responses from institutions
*
* @param files a list files that will be uploaded
*/
@Override
public boolean store(List<MultipartFile> files, Path path) {
try {
for (MultipartFile file : files) {
if (file.isEmpty()) {
continue; // give me another one
}
byte[] bytes = file.getBytes();
Files.write(path, bytes);
}
} catch (IOException ioe) {
logger.error(ioe.getStackTrace());
return false;
}
return true;
}
示例13: isPhoto
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
/**
* 判斷上傳文件是否為圖片
*
* @param MultipartFile
* @return NULL為TRUE
*/
public static boolean isPhoto(MultipartFile file) {
if (file == null) {
return false;
}
String originalFilename = file.getOriginalFilename();
if (originalFilename == null || originalFilename.length() == 0) {
return false;
}
// 獲取文件後綴
String fileSuffix = UploadUtil.getFileSuffix(originalFilename);
if (fileSuffix == null || fileSuffix.length() == 0) {
// 通過Mime類型獲取文件類型
fileSuffix = ContentTypeUtil.getFileTypeByMimeType(file.getContentType());
}
if(fileSuffix==null || fileSuffix.equals("")) {
return false;
}
if(PhotoSuffix.indexOf(fileSuffix.toLowerCase()) != -1){
return true;
}
return false;
}
示例14: processUpload
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
/**
* 上傳發布流程定義.
*/
@RequestMapping("console-process-upload")
public String processUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) throws Exception {
String tenantId = tenantHolder.getTenantId();
String fileName = file.getOriginalFilename();
Deployment deployment = processEngine.getRepositoryService()
.createDeployment()
.addInputStream(fileName, file.getInputStream())
.tenantId(tenantId).deploy();
List<ProcessDefinition> processDefinitions = processEngine
.getRepositoryService().createProcessDefinitionQuery()
.deploymentId(deployment.getId()).list();
for (ProcessDefinition processDefinition : processDefinitions) {
processEngine.getManagementService().executeCommand(
new SyncProcessCmd(processDefinition.getId()));
}
return "redirect:/bpm/console-listProcessDefinitions.do";
}
示例15: uploadFile
import org.springframework.web.multipart.MultipartFile; //導入依賴的package包/類
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public View uploadFile(@RequestParam("file") MultipartFile file) {
try {
InputStream input = file.getInputStream();
this.messageManagementService.importFromExcel(input);
} catch (Exception e) {
LOG.error("error on uploading messages", e);
return new RedirectView("../files.html?uploadSuccess=no&message=" + e.getMessage().toString());
}
return new RedirectView("../files.html?uploadSuccess=yes");
}