Поделитесь загрузкой и загрузкой файла и сжимайте изображение, используемое в проекте, и непосредственно извлечено из проекта :)
Кода -копия выглядит следующим образом:
пакет com.eabax.plugin.yundada.utils;
Импорт java.awt.image.bufferedImage;
Импорт java.io.file;
импортировать java.io.ioexception;
импортировать java.text.simpledateformat;
импортировать java.util.date;
импортировать java.util.list;
импортировать java.util.uuid;
Импорт javax.imageio.imageio;
Импорт javax.servlet.http.httpservletrequest;
Импорт net.coobird.thumbnailator.thumbnails;
Импорт org.apache.commons.fileupload.fileitem;
Import org.apache.commons.fileupload.disk.diskfileitemfactory;
Import org.apache.commons.fileupload.servlet.servletfileUpload;
Импорт org.json.jsonobject;
Импорт org.slf4j.logger;
Импорт org.slf4j.loggerfactory;
Импорт com.eabax.plugin.yundada.gacontext;
открытый класс fileUploaddownloadutil {
Private Static Final Logger log = loggerFactory.getLogger (fileUploadDownloadUtil.class);
/**
* Загружать файлы на сервер
* @param запрос
* @param type
* @возвращаться
* @ThrohS Exception
*/
Общедоступная статическая строка загрузка (httpservlectrequest, тип строки) бросает исключение {
Boolean Ismultipart = ServletFileUpload.ismultipartContent (запрос);
String SaveFilename = null;
if (ismultipart) {
String savePath = request.getSession (). GetServletContext ()
.getRealPath ("/")
+ "/upload/";
String Temppath = request.getSession (). GetServletContext ()
.getRealPath ("/")
+ "/upload/temp/";
File savefile = new File (savePath);
File tempfile = new File (Temppath);
if (! savefile.isdirectory ())
saveFile.mkdirs ();
if (! tempfile.isdirectory ())
tempfile.mkdirs ();
DiskFileItemfactory Factory = new DiskFileItemFactory ();
factory.setsizethershold (1024 * 4);
factory.setrepository (tempfile);
ServletFileUpload uploader = new ServletFileUpload (Factory);
uploader.setsizemax (20 * 1024 * 1024);
List <FieleItem> fileItems = uploader.parserequest (request);
для (FileItem Item: fileItems) {
if (item.isformfield ()) {
// funname = item.getString ();
} еще {
// string fileName = item.getName ();
// Нить
// fix = filename.substring (filename.lastindexof (".")+1);
String fix = type;
Date owndate = new Date ();
SimpleDateFormat SDF = new SimpleDateFormat (
"yyyymmddhhmmss");
String fileName = sdf.format (owndate);
fileName += System.CurrentTimeMillis ();
имя файла + = "." + Исправлена;
saveFilename = "/upload/" + filename;
File file = new File (SavePath + FileName);
item.write (file);
}
}
}
вернуть SaveFilename;
}
/**
* Загрузите аватар
* @param запрос
* @param type
* @возвращаться
* @ThrohS Exception
*/
Public Static String uploadHeadShow (httpservletRequest, контекст Gacontext, тип строки) бросает исключение {
Boolean Ismultipart = ServletFileUpload.ismultipartContent (запрос);
String SaveFilename = null;
String ImagePath = "/upload/Headshow/";
String x = request.getParameter ("длина");
String y = request.getParameter ("Wide");
if (ismultipart) {
String HeadShowserServicePath = request.getSession (). GetServletContext ()
.getRealPath ("/")
+ ImagePath;
Date owndate = new Date ();
SimpleDateFormat SDF = new SimpleDateFormat (
"yyyymmddhhmmss");
String fileName = context.getUsername ()+sdf.format (wyldate);
File HeadShowFile = новый файл (HeadShowServicePath);
if (! Headshowfile.isdirectory ())
Headshowfile.mkdirs ();
DiskFileItemfactory Factory = new DiskFileItemFactory ();
factory.setsizethershold (1024 * 4);
factory.setRepository (Headshowfile);
ServletFileUpload uploader = new ServletFileUpload (Factory);
uploader.setsizemax (20 * 1024 * 1024);
List <FieleItem> fileItems = uploader.parserequest (request);
для (FileItem Item: fileItems) {
if (item.isformfield ()) {
// funname = item.getString ();
} еще {
String fix = type;
имя файла + = "." + Исправлена;
saveFilename = imagePath + имя файла;
File file = новый файл (HeadShowserVicePath + FileName);
item.write (file);
}
}
// Сжатие изображения
if (x! = null &&! "",. Equals (x) && y! = null &&! "",. Equals (y)) {
SaveFilename = ThumbnailatorImage (ImagePath, имя файла, тип, integer.parseint (x), integer.parseint (y));
}
}
вернуть SaveFilename;
}
/**
* Загружать и поделиться фотографиями
* @param запрос
* @param type
* @возвращаться
* @ThrohS Exception
*/
public static jsonObject uploadArticleImage (httpservletrequest, контекст Gacontext, тип строки), бросает исключение {
Boolean Ismultipart = ServletFileUpload.ismultipartContent (запрос);
JsonObject saveFilename = new jsonObject ();
String ImagePath = "";
String x = request.getParameter ("длина");
String y = request.getParameter ("Wide");
if ("4" .equals (type)) {
// Поделитесь пути загрузки изображения
ImagePath = "/upload/articleImage/";
} else if ("5" .equals (type)) {
// Связанный путь загрузки образа образа
ImagePath = "/upload/linkimage/";
} еще {
// путь к загрузке аватара
ImagePath = "/upload/Headshow/";
}
if (ismultipart) {
String HeadShowserServicePath = request.getSession (). GetServletContext ()
.getRealPath ("/")
+ ImagePath;
File HeadShowFile = новый файл (HeadShowServicePath);
if (! Headshowfile.isdirectory ())
Headshowfile.mkdirs ();
DiskFileItemfactory Factory = new DiskFileItemFactory ();
factory.setsizethershold (1024 * 4);
factory.setRepository (Headshowfile);
ServletFileUpload uploader = new ServletFileUpload (Factory);
uploader.setsizemax (20 * 1024 * 1024);
List <FieleItem> fileItems = uploader.parserequest (request);
для (FileItem Item: fileItems) {
Uuid uuid = uuid.randomuuid ();
String fileName = uuid.toString ();
if (item.isformfield ()) {
// funname = item.getString ();
} еще {
String fix = type;
имя файла + = "." + Исправлена;
saveFilename.put (uuid.toString (), imagePath + имя файла);
File file = новый файл (HeadShowserVicePath + FileName);
item.write (file);
}
// Сжатие изображения
if (x! = null &&! "",. Equals (x) && y! = null &&! "",. Equals (y)) {
String thumbnailAtorname = ThumbnailatorImage (ImagePath, имя файла, тип, integer.parseint (x), Integer.parseint (y));
saveFilename.put ("ThumbnailatorImage", ThumbnaIlatorName);
}
}
}
вернуть SaveFilename;
}
/**
* Загрузить сжатие и сохранить изображения
* @param oldsavepath оригинальный путь файла
* @param oldfilename Имя файла исходного файла
* @param исправить тип файла
* @param x ширина, необходимая для сжатия
* @param y длина, необходимая для сжатия
* @возвращаться
* @Throws ioException
*/
Public Static String ThumbNailatorImage (String OldSavePath, String OldFilename, String Fix, Int X, Int Y) бросает ioException {
// Миниатюра читает и сжимает картинки
BufferedImage watermarkeredimage = thumbnails.of (Oldsavepath+OldFilename)
// Метод миниатюры, сжатие изображений
.size (x, y)
// Читать как объект BuffereMage
. AsbufferedImage ();
// записать изображения в памяти в указанный файл
String SavePath = OldSavePath+x+"-"+y+"/";
File savefile = new File (savePath);
if (! savefile.isdirectory ())
saveFile.mkdirs ();
DiskFileItemfactory Factory = new DiskFileItemFactory ();
factory.setsizethershold (1024 * 4);
factory.setRepository (saveFile);
ServletFileUpload uploader = new ServletFileUpload (Factory);
uploader.setsizemax (20 * 1024 * 1024);
Uuid uuid = uuid.randomuuid ();
String fileName = uuid.toString ();
имя файла + = "." + Исправлена;
String SaveFilename = SavePath+FileName;
FileOutput = новый файл (saveFilename);
Imageio.Write (WaterMarkEfferedImage, Fix, FileOutput);
вернуть SaveFilename;
}
/**
* Скачать сжатые и сохранить картинки
* @param oldsavepath оригинальный путь файла
* @param oldfilename Имя файла исходного файла
* @param исправить тип файла
* @param x ширина, необходимая для сжатия
* @param y длина, необходимая для сжатия
* @возвращаться
* @Throws ioException
*/
Public Static String Download ThroubnailatorImage (String ServicePath, String URI, int x, int y) бросает ioException {
// Проверьте, существует ли изображение
String urisubpath = uri.substring (0, uri.lastindexof ("/")+1); // Перед именем файла после сервера
String fileName = uri.substring (uri.lastindexof ("/")+1, uri.length ()); // Имя файла
String getTheumbNailatorPath = servicePath+urisubpath+x+"-"+y+"/";
String SaveFilename = getThumbNailatorPath+имя файла;
File DownFilePath = новый файл (getThumbNailatorPath); // Сжатие папки после сжатия
File downfile = new File (saveFilename); // Сжатие файла после него
if (downfilepath.isdirectory () && downfile.exists ()) {
вернуть SaveFilename;
} еще {
// Миниатюра читает и сжимает картинки
log.Error (ServicePath+URI);
BufferedImage watermarkefferedimage = thumbnails.of (ServicePath+URI)
// Метод миниатюры, сжатие изображений
.size (x, y)
// Читать как объект BuffereMage
. AsbufferedImage ();
if (! downfilepath.isdirectory ()) {
downfilepath.mkdirs ();
}
DiskFileItemfactory Factory = new DiskFileItemFactory ();
factory.setsizethershold (1024 * 4);
Factory.SetRepository (DownFilePath);
ServletFileUpload uploader = new ServletFileUpload (Factory);
uploader.setsizemax (20 * 1024 * 1024);
FileOutput = новый файл (saveFilename);
Imageio.Write (WaterMarkEfferedImage, "jpg", fileOutput);
}
вернуть SaveFilename;
}
}
Вышеупомянутое - весь контент, разделенный в этой статье, я надеюсь, что это будет полезно для всех.